﻿/* Global variables
---------------------------------------------------------------- */

var tictim;
var bretim;
var sliding = false;


/* Toogle text
---------------------------------------------------------------- */

var field = function() {
    return {
        focus: function(f, txt) {
            if (f.value == txt) {
                f.value = '';
            } else {
                f.select();
            }
        },
        blur: function(f, txt) {
            if (f.value == '') {
                f.value = txt;
            }
        }
    };
} ();

/* Link function
---------------------------------------------------------------- */

var url = function() {
    return {
        href: function(url, blank) {
            if (blank) {
                window.open(url);
            } else {
                location.href = url;
            }
        }
    };
} ();

/* Ajax <|> ajax.load('http://','ajaxdiv',true,['customfunction()','anotherfunction()']);
---------------------------------------------------------------- */

var ajax = function() {
    return {
        nocache: function() {
            var minutes = 1000 * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var d = new Date();
            var t = d.getTime();
            return t;
        },
        load: function(url, container, load, functions) {
            var obj = document.getElementById(container);
            var loader = '<div class="loading"></div>';
            if (obj && url) {
                if (load) { obj.innerHTML = loader; }
                ajax.page(url, container, functions);
            }
        },
        page: function(url, container, functions) {
            var _url, _no;
            if (url.indexOf("?") == -1) { _no = '?~' + ajax.nocache(); } else { _no = '&~' + ajax.nocache(); }
            _url = url + _no;

            if (window.XMLHttpRequest) {
                page_request = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                try {
                    page_request = new ActiveXObject('Msxml2.XMLHTTP');
                } catch (e) {
                    try {
                        page_request = new ActiveXObject('Microsoft.XMLHTTP');
                    } catch (e) { }
                }
            } else {
                return false;
            }

            page_request.onreadystatechange = function() {
                ajax.parse(page_request, container, functions);
            }
            page_request.open('GET', _url, true);
            page_request.send(null);
        },
        parse: function(page_request, container, functions) {
            if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf('http') == -1)) {
                document.getElementById(container).innerHTML = page_request.responseText;
                ajax.completed(functions);
            }
        },
        completed: function(functions) {
            // After complete functions here..
            if (functions) {
                for (var i = 0; i < functions.length; i++) {
                    try { eval(functions[i]); } catch (e) { alert(e.description); }
                }
            }
        }
    };
} ();

/* Validation
---------------------------------------------------------------- */

var validate = function() {
    var execute = true;
    return {
        err: function(step, f) {
            var obj = document.getElementById(f);
            if (obj) {
                if (step == '1') { obj.style.backgroundColor = '#ffabab'; setTimeout("validate.err('2','" + f + "');", 50); }
                if (step == '2') { obj.style.backgroundColor = '#ffc5c5'; setTimeout("validate.err('3','" + f + "');", 50); }
                if (step == '3') { obj.style.backgroundColor = '#ffdfdf'; setTimeout("validate.err('4','" + f + "');", 50); }
                if (step == '4') { obj.style.backgroundColor = '#fef1f1'; setTimeout("validate.err('5','" + f + "');", 50); }
                if (step == '5') { obj.style.backgroundColor = '#fff'; }
            }
        },
        email: function(str) {
            var filter = /^[^\s@]+@[^\s@]+\.[a-z]{2,6}$/i;
            if (filter.test(str)) { return true; } else { return false; }
        },
        empty: function(str) {
            var filter = /^\s+$/;
            var expression;
            if (filter.test(str) || str == '') { expression = false; } else { expression = true; }
            return expression;
        },
        onlynumbers: function(evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } else { return true; }
        },
        search: function(f, txt) {
            execute = true;
            if (!validate.empty(f.q.value) || f.q.value == txt) {
                execute = false;
                validate.err('1', f.q.id);
            }
            return execute;
        }
    };
} ();

/* Tips
---------------------------------------------------------------- */

var tip = function() {
    var chglink = '';
    return {
        show: function(f, m) {
            var lnk = document.getElementById('sharepagelink');
            var obj = document.getElementById(m);
            if (obj && lnk) {
                if (f.className == 'share' || f.className == 'share-active') { chglink = f.id; f.className = 'share-active'; }
                if (obj.style.display == 'block') {
                    tip.hide(f, m);
                } else {
                    var str = library.elementposition(lnk);
                    var tmp = str.split('/');
                    var lnkx = parseInt(tmp[0]) + (obj.offsetWidth / 2);
                    var lnky = parseInt(tmp[1]) - (obj.offsetHeight) - 2;
                    obj.style.left = lnkx + 'px';

                    var ua = window.navigator.userAgent
                    var msie = ua.indexOf("MSIE ")
                    if (msie > 0) {
                        lnky += 35;
                    }
                    obj.style.top = lnky + 'px';
                    slider.toogle(m);
                }
                f.blur();
            }
        },
        hide: function(f, m) {
            var obj = document.getElementById(m);
            if (obj) { slider.toogle(m); }
            if (chglink != '') { var elm = document.getElementById(chglink); if (elm) { elm.className = 'share'; chglink = ''; } }
        }
    };
} ();

/* Menu
---------------------------------------------------------------- */

var menu = function() {
    return {
        click: function(f) {
            var m = f.id + '-child';
            var obj = document.getElementById(m);
            if (obj) {
                if (obj.style.display == 'block' || obj.className == 'show') {
                    f.className = '';
                    obj.className = '';
                    slider.up(m);
                } else {
                    f.className = 'selected';
                    slider.down(m);
                }
                f.blur();
            }
        },
        crumb: function() {
            var obj = document.getElementById('crumb');
            var fix = document.getElementById('crumb-fix');
            if (obj) {
                var elmH = obj.offsetHeight;
                if (elmH > 18) {
                    fix.style.paddingTop = '-12px';
                }
            }
        }
    };
} ();

/* Sliding divs <|> slider.toogle('divname',['customfunction()','anotherfunction()']);
---------------------------------------------------------------- */

var slider = function() {
    var sliding = false, slideAtClose = true, duration = 0.3, obj, newHeight, curHeight;
    return {
        init: function(elm) {
            obj = document.getElementById(elm);
            if (obj.style.display == '' || obj.style.display == 'none') {
                obj.style.display = 'block';
                obj.style.height = parseInt(obj.offsetHeight) + 'px';
                obj.style.display = 'none';
            } else if (obj.style.display == 'block') {
                obj.style.display = 'block';
                obj.style.height = parseInt(obj.offsetHeight) + 'px';
            }
        },
        toogle: function(elm, functions) {
            obj = document.getElementById(elm);
            if (obj.style.display == '' || obj.style.display == 'none') {
                slider.down(elm, functions);
            } else {
                slider.up(elm, functions);
            }
        },
        down: function(elm, functions) {
            if (!sliding) {
                slider.init(elm);
                newHeight = parseInt(obj.style.height);
                curHeight = '1';
                obj.style.height = '1px';
                obj.style.display = 'block';
                slider.slide(elm, functions);
            }
        },
        up: function(elm, functions) {
            if (!sliding) {
                slider.init(elm);
                curHeight = parseInt(obj.style.height);
                newHeight = '1';
                var finishTime = slider.slide(elm, functions);
                window.setTimeout("slider.hide();", finishTime);
            }
        },
        slide: function(elm, functions) {
            sliding = true;
            var frames = 30 * duration;
            var tinc = (duration * 1000) / frames;
            tinc = Math.round(tinc);
            var sinc = (curHeight - newHeight) / frames;
            var frameSizes = new Array();
            for (var i = 0; i < frames; i++) {
                if (i < frames / 2) {
                    frameSizes[i] = (sinc * (i / frames)) * 4;
                } else {
                    frameSizes[i] = (sinc * (1 - (i / frames))) * 4;
                }
            }
            for (var i = 0; i < frames; i++) {
                curHeight = curHeight - frameSizes[i];
                window.setTimeout("document.getElementById('" + elm + "').style.height = '" + Math.round(curHeight) + "px';", tinc * i);
                if ((i + 1) == frames) { window.setTimeout("slider.complete(" + functions + ");", tinc * (i + 5)); }
            }
            return tinc * i;
        },
        hide: function() {
            obj.style.display = 'none';
        },
        auto: function() {
            obj.style.height = 'auto';
        },
        complete: function(functions) {
            sliding = false;
            slider.auto();
            if (functions) {
                for (var i = 0; i < functions.length; i++) {
                    try { eval(functions[i]); } catch (e) { alert(e.description); }
                }
            }
        }
    };
} ();

/* Ticker
---------------------------------------------------------------- */

var ticker = function() {

    return {

        // id (the container to slide)
        // auto (timer - slide the slideshow automatically)
        // wid (the width to slide the container each time)
        initialize: function(f, auto, wid) {
            // Set objects (container + slideshow controls)

            var obj = document.getElementById(f);
            var elm = document.getElementById(f + '-controls');
            if (obj) {

                // Count the number of items in container
                var tickers = ticker.count(f);

                // If there is more than one container, then continue
                if (tickers > 1) {
                    // If the slider controls container exists, then continue
                    if (elm) {
                        // Reset container contents
                        elm.innerHTML = '';
                        // Loop through each of the counted containers
                        for (var d = 0; d < tickers; d += 1) {
                            // Array starts with 0, we want 1, 2, 3, not 0, 1, 2, so add one to array counter
                            var dc = d + 1;
                            // If it is the first item, then set indicator to current
                            if (d == 0) {
                                elm.innerHTML += '<li id="' + f + '-itm' + (dc) + '" class="current" onclick="ticker.click(\'' + (dc) + '\',true,\'' + f + '\',\'' + wid + '\');"><span></span></li>';
                            } else {
                                elm.innerHTML += '<li id="' + f + '-itm' + (dc) + '" onclick="ticker.click(\'' + (dc) + '\',true,\'' + f + '\',\'' + wid + '\');"><span></span></li>';
                            }
                        }
                    }
                }
                // If the container is to autoslide
                if (auto) {
                    // If it is the ticker container
                    if (f == 'ticker') {
                        // Set a timer with interval 15 seconds
                        tictim = setInterval("ticker.auto('" + f + "','" + wid + "');", 15000);
                    } else if (f == 'breaking') {
                        // Set a timer with interval 16 seconds
                        bretim = setInterval("ticker.auto('" + f + "','" + wid + "');", 16000);
                    }
                }
            }
        },
        // When user clicks a indicator
        // num (the indicators number)
        // m (break the timer "true/false" - used when user clicks on the indicator)
        // f (the main container)
        // wid (the width to slide the container each time)
        click: function(num, m, f, wid) {
            // Reset the indicators classnames
            ticker.reset(f);
            // The current indicator
            var elm = document.getElementById(f + '-itm' + num);
            // Set the indicator to current (classname) + blur the click
            if (elm) { elm.className = 'current'; elm.blur(); }
            // Call toogle function
            ticker.toogle(num, f, wid);
            // If user has clicked the indicator, then clear the auto timer
            if (m) { if (f == 'ticker') { clearInterval(tictim); } else if (f == 'breaking') { clearInterval(bretim); } }
        },
        // f (the main container)
        // wid (the width to slide the container each time)
        back: function(f, wid) {
            // Set object (slideshow controle)
            var obj = document.getElementById(f + '-controls');
            // Count controls items
            var items = obj.getElementsByTagName('li');
            // Reset counter (all), reset current counter
            var all = 0; var iscur = 0;
            // Loop through items
            for (var d = 0; d < items.length; d += 1) {
                // Count all
                all++;
                // If the indicator is the current, then give iscur the current count value
                if (items[d].className == 'current') { iscur = all; }
            }
            var next;
            // Find the next item
            if (iscur == 1) { next = all; } else { next = iscur - 1; }
            // Tricker (click) the next indicator
            ticker.click(next, false, f, wid);
        },
        // f (the main container)
        // wid (the width to slide the container each time)
        forward: function(f, wid) {
            // Set object (slideshow controle)
            var obj = document.getElementById(f + '-controls');
            // Count controls items
            var items = obj.getElementsByTagName('li');
            // Reset counter (all), reset current counter
            var all = 0; var iscur = 0;
            // Loop through items
            for (var d = 0; d < items.length; d += 1) {
                all++;
                // If the indicator is the current, then give iscur the current count value
                if (items[d].className == 'current') { iscur = all; }
            }
            var next;
            // Find the next item
            if (iscur == all) { next = 1; } else { next = iscur + 1; }
            // Tricker (click) the next indicator
            ticker.click(next, false, f, wid);
        },
        // This part is used to auto slide the container
        // f (the main container)
        // wid (the width to slide the container each time)
        auto: function(f, wid) {
            // Set object (slideshow controle)
            var obj = document.getElementById(f + '-controls');
            // Count controls items
            var items = obj.getElementsByTagName('li');
            // Reset counter (all), reset current counter
            var all = 0; var iscur = 0;
            // Loop through items
            for (var d = 0; d < items.length; d += 1) {
                all++;
                // If the indicator is the current, then give iscur the current count value
                if (items[d].className == 'current') { iscur = all; }
            }
            var next;
            // Find the next item
            if (iscur == all) { next = 1; } else { next = iscur + 1; }
            // Tricker (click) the next indicator
            ticker.click(next, false, f, wid);
        },
        // num (the indicators number)
        // f (the main container)
        // wid (the width to slide the container each time)
        toogle: function(num, f, wid) {
            // Set object (container)
            var obj = document.getElementById(f);
            // Reset from variable, starts from 0, then moves
            var _from = 0;
            // Get real/current left position (if already moved)
            _from = parseInt(obj.style.left);
            // If it return no number, then set to 0, set object style, else set as measured above
            if (isNaN(_from)) { _from = 0; obj.style.left = '0px'; } else { _from = _from; }
            // Move the container to (from -> to position)
            var _to = _from - (_from + ((num - 1) * wid));
            // Tricker mover function
            mover.move(f, _from, _to);
        },
        // f (the main container)
        reset: function(f) {
            // Set object (slideshow controle)
            var obj = document.getElementById(f + '-controls');
            // Count controls items
            var items = obj.getElementsByTagName('li');
            // Loop through items
            for (var d = 0; d < items.length; d += 1) {
                // Reset classname
                items[d].className = '';
            }
        },
        // f (the main container)
        count: function(f) {
            // Set object (container)
            var obj = document.getElementById(f);
            // Reset counter
            var count = 0;
            // Count number of divs
            var items = obj.getElementsByTagName('div');
            // Loop through items
            for (var d = 0; d < items.length; d += 1) {
                // If the div has class itm, then add to count
                if (items[d].className == 'itm') {
                    count++;
                }
            }
            // Return number
            return count;
        }
    };
} ();

/* Move divs <|> slider.toogle('divname',['customfunction()','anotherfunction()']);
---------------------------------------------------------------- */

var mover = function() {
    var slideAtClose = true, duration = 0.6, obj, newLeft, curLeft;
    return {
        init: function(elm, from) {
            obj = document.getElementById(elm);
            if (obj) { obj.style.left = from + 'px'; }
        },
        move: function(elm, from, to, functions) {
            if (!sliding) {
                mover.init(elm, from);
                newLeft = to;
                curLeft = from;
                mover.slide(elm, functions);
            }
        },
        slide: function(elm, functions) {
            sliding = true;
            var frames = 30 * duration;
            var tinc = (duration * 1000) / frames;
            tinc = Math.round(tinc);
            var sinc = (curLeft - newLeft) / frames;
            var frameSizes = new Array();
            for (var i = 0; i < frames; i++) {
                if (i < frames / 2) {
                    frameSizes[i] = (sinc * (i / frames)) * 4;
                } else {
                    frameSizes[i] = (sinc * (1 - (i / frames))) * 4;
                }
            }
            for (var i = 0; i < frames; i++) {
                curLeft = curLeft - frameSizes[i];
                window.setTimeout("document.getElementById('" + elm + "').style.left = '" + Math.round(curLeft) + "px';", tinc * i);
                if ((i + 1) == frames) { window.setTimeout("mover.complete(" + functions + ");", tinc * (i + 5)); }
            }
        },
        hide: function() {
            obj.style.height = 'auto';
            obj.style.display = 'none';
        },
        complete: function(functions) {
            sliding = false;
            if (functions) {
                for (var i = 0; i < functions.length; i++) {
                    try { eval(functions[i]); } catch (e) { alert(e.description); }
                }
            }
        }
    };
} ();

/* Cookies
---------------------------------------------------------------- */

var cookies = function() {
    return {
        create: function(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        },
        read: function(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        },
        erase: function(name) {
            cookies.create(name, "", -1);
        }
    };
} ();

/* Library
---------------------------------------------------------------- */

var library = function() {
    return {
        elementposition: function(obj) {
            var curleft = curtop = 0;
            if (obj.offsetParent) {
                curleft = obj.offsetLeft;
                curtop = obj.offsetTop;
                while (obj = obj.offsetParent) {
                    curleft += obj.offsetLeft
                    curtop += obj.offsetTop
                }
            }
            return curleft + '/' + curtop;
        },
        cursorposition: function(e) {
            e = e || window.event;
            var cursor = { x: 0, y: 0 };
            if (e.pageX || e.pageY) {
                cursor.x = e.pageX;
                cursor.y = e.pageY;
            } else {
                var de = document.documentElement;
                var b = document.body;
                cursor.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
                cursor.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
            }
            return cursor.x + '/' + cursor.y;
        },
        documentdimensions: function() {
            var myWidth = 0, myHeight = 0;
            if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
            } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
            } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
            }
            return myWidth + '/' + myHeight;
        },
        whichelement: function(e) {
            var targ, found = false;
            if (!e) { var e = window.event; }
            if (e.target) { targ = e.target; } else if (e.srcElement) { targ = e.srcElement; }
            if (targ.nodeType == 3) { targ = targ.parentNode; }
            if (targ.className == 'contextmenu') { found = true; } else { found = false; }
            return found;
        },
        keycode: function(evt) {
            evt = (evt) ? evt : ((event) ? event : null);
            var evver = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
            var keynumber = evt.keyCode;
            if (keynumber) { return keynumber; }
        }
    };
} ();

window.onload = function() {

    
// Initialize the sliders
    ticker.initialize('ticker', true, 490);
    ticker.initialize('carousel', false, 100);
    // Initialize crumb bread fixer
    menu.crumb();
}
