/*  ------------------------------------------------------------------
    Functions -------------------------------------------------------- */

    /*  ------------------------------------------------------------------
        switchSize ------------------------------------------------------- */
        function switchTextSize(size, settings) {
            if(size !== ''){
                $('body').removeClass().addClass(size);
                if (settings.saveCookie === true) {
                    $.cookie('textsize', size, { expires: 365, path: '/'  });
                }
            }
        }


    /*  ------------------------------------------------------------------
        Send to a Friend ------------------------------------------------- */
        function openSTF(target, node){
            var $stf = $('#stf');
            var isIE6 = false;
            if($.browser.msie && $.browser.version < 7){ var isIE6 = true; }

            //dcsMultiTrack('DCS.dcsuri','/Sendtoafriend/');

            if(!$stf.hasClass('loaded')) {
                $stf.load("/tisendtofriend/template/sendtofriend/"+node, function() {
                    $stf.addClass('loaded').insertBefore('#content');
                    $.scrollTo(target, 500, { onAfter: function(){
                        if (isIE6) { $stf.show(); } else { $stf.slideDown(); }
                    }});
                });
            } else {
                $.scrollTo(target, 500, { onAfter: function(){
                    if (isIE6) { $stf.show(); } else { $stf.slideDown(); }
                }});
            }
        };

        function closeSTF(which){
            if($.browser.msie && $.browser.version < 7){ $(which).hide(); } else { $(which).slideUp(); }
            return false;
        };

        function validateSTF(errorMap, ErrorList) {
            var messages = '';
            var countErrors = 0;
            for (var i = 0; this.errorList[i]; i++) {
                var error = this.errorList[i];
                this.settings.highlight && this.settings.highlight.call(this, error.element, this.settings.errorClass, this.settings.validClass);
                if((error.element.id == 'frm_stf_your_email' && error.message != '')||(error.element.id == 'frm_stf_friends_email' && error.message != '')) {
                    message = error.message;
                    countErrors++;
                }
            }
            if (this.errorList.length) {
                if(this.errorList.length == countErrors && message){
                    this.containers.find(".stf_required").html(message).show();
                    this.containers.find(".stf_generic").hide();
                }else{
                    this.containers.find(".stf_required").hide();
                    this.containers.find(".stf_generic").show();
                }
            } 
            if (this.settings.unhighlight) {
                for (var i = 0, elements = this.validElements(); elements[i]; i++) {
                    this.settings.unhighlight.call(this, elements[i], this.settings.errorClass, this.settings.validClass);
                }
            }
        }


/*  ------------------------------------------------------------------
    Extend jQuery Functions ------------------------------------------ */
    (function ($) {
    /*  ------------------------------------------------------------------
        Matching Height -------------------------------------------------- */
        $.fn.matchHeight = function() {
            var mh = 0;
            $('li', this).each(function(i){
                if($(this).height() > mh) { mh = $(this).height(); }
            });
            return $('li', this).each(function(i){
                $(this).css('height', mh);
            });
        };


    /*  ------------------------------------------------------------------
        Vertical Align --------------------------------------------------- */
        $.fn.verticalAlign = function() {
            return this.each(function(i){
            var ah = $(this).height();
            var ph = $(this).parent().height();
            var mh = (ph - ah) / 2;
            $(this).css('margin-top', mh);
            });
        };


    /*  ------------------------------------------------------------------
        switchSize ------------------------------------------------------- */
        $.fn.switchSize = function(settings) {
            // defaults settings
            settings = $.extend({
                saveCookie: true
            },settings);

            return this.each(function(){
                var container = this;
                var curtextsize = $.cookie('textsize');
                if (curtextsize) { $('body').removeClass().addClass(curtextsize); }

                $(this)
                    .find("a")
                    .bind('click', function(){
						location.href = $(this).attr("href");
                        switchTextSize( $(this).attr("rel"), settings);
                        return false;
                    });
            });
        };


    /*  ------------------------------------------------------------------
        Plugin/Cookie ---------------------------------------------------- */
        $.cookie = function(name, value, options) {
            if (typeof value != 'undefined') { // name and value given, set cookie
                options = options || {};
                if (value === null) {
                    value = '';
                    options.expires = -1;
                }
                var expires = '';
                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                    var date;
                    if (typeof options.expires == 'number') {
                        date = new Date();
                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    } else {
                        date = options.expires;
                    }
                    expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
                }
                // CAUTION: Needed to parenthesize options.path and options.domain
                // in the following expressions, otherwise they evaluate to undefined
                // in the packed version for some reason...
                var path = options.path ? '; path=' + (options.path) : '';
                var domain = options.domain ? '; domain=' + (options.domain) : '';
                var secure = options.secure ? '; secure' : '';
                document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
            } else { // only name given, get cookie
                var cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
        };


    })(jQuery);


/*  ------------------------------------------------------------------
    On Load ---------------------------------------------------------- */
    $(function(){

    /*  ------------------------------------------------------------------
        JavaScript Disabled Warning -------------------------------------- */
        $("body").css("padding-top","0");

    /*  ------------------------------------------------------------------
        Browser IE6 ------------------------------------------------------ */
        var isIE6 = false;
        if($.browser.msie && $.browser.version < 7){ var isIE6 = true; }


    /*  ------------------------------------------------------------------
        Vertical Align --------------------------------------------------- */
        $('a.m2_link span').verticalAlign();
        $('.valign').verticalAlign();


    /*  ------------------------------------------------------------------
        AJAX ------------------------------------------------------------- */
        $("#ajax_loading") 
        .ajaxStart(function(){ $(this).show(); $("body").css("cursor", "wait"); })
        .ajaxStop(function() { $(this).hide(); $("body").css("cursor", "default"); });


    /*  ------------------------------------------------------------------
        Remove default value on Focus ------------------------------------ */
        $("input[@type*='text'][title]:not('.required')")
        .bind("focus",function(){ if(this.value==this.title){ this.value=""; } })
        .bind("blur",function(){ if(this.value==""){ this.value=this.title; } });


    /*  ------------------------------------------------------------------
        Footer - Main Sites ---------------------------------------------- */
        $("a", ".mainother").hover(
            function(){ $(this).siblings("p").show(); },
            function(){ $(this).siblings("p").hide(); }
        );
        $("ul", ".mainother").hover(
            function(){ $(this).siblings("p").show(); },
            function(){ $(this).siblings("p").hide(); }
        );


    /*  ------------------------------------------------------------------
        Send to a Friend ------------------------------------------------- */
        $("#b_stf").bind("click", function(){
			location.href = $(this).attr("href");
            if($("#stf").css("display")=="none"){
                openSTF(this.href, $(this).attr("rel"));
            }else{
                closeSTF('#stf');
            }
            return false;
        });


    /*  ------------------------------------------------------------------
        Bottom Bar Scroll ------------------------------------------------ */
        $(".prev, .prevPage, .next, .nextPage").show();
        var $bottombar_scroll = $("div.scrollable").scrollable({ api:true, keyboard:false, size:6, speed:800 });
        if($bottombar_scroll && $bottombar_scroll.getSize() < 7){ $bottombar_scroll.getNaviButtons().hide(); }


    /*  ------------------------------------------------------------------
        Sharing Utilities Popup ------------------------------------------ */
        var popFeatures = "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,width=700,height=400";
        $("a:not(a[id='b_stf'])", "#list_sharing").bind("click", function(){
			location.href = "#utilities-share-" + $(this).attr("rel");
            window.open(this.href, 'pop_'+$(this).text(), popFeatures);
            return false;
        });


    /*  ------------------------------------------------------------------
        External Link ---------------------------------------------------- */
        var allowedDomains = [location.hostname];
        $("a[href^=http]:not(.internal):not([rel^='popup'])")
        .filter(function(el){
            for ( var i=0; i < allowedDomains.length; i++ ) {
                if ( this.href.indexOf(allowedDomains[i])>-1 ) return false;
            }
            return true;
        }).bind("click", function(){ return !window.open(this.href); });


    /*  ------------------------------------------------------------------
        Font Switcher ---------------------------------------------------- */
        $("#fontswitcher").switchSize();


    /*  ------------------------------------------------------------------
        Popup ------------------------------------------------------------ */
        $("a[rel^='popup']").bind("click", function(){
            rel = $(this).attr("rel");
            rel = rel.replace("popup", "").split("x");
            w = rel[0];
            h = rel[1];
            return !window.open(this.href, this.href, "location=1, status=1, scrollbars=1, menubar=1, toolbar=1, width="+w+", height="+h);
        });


    /*  ------------------------------------------------------------------
        Utilities -------------------------------------------------------- */
        $("#utilities").show();
        var utilities_marginright = $("#utilities").css("margin-right");
        var expanded = false;
        var closeTimeUtilities = false;
        var closeUtilities = false;

        $("#utilities_icon").click(function(){
            if(expanded){
                expanded = false;
                if(isIE6){
                    $("#utilities").css("width", "38px");
                    $("#utilities_options").hide();
                }else{
                    $("#utilities").animate({marginRight:utilities_marginright}, 'normal', 'swing');
                }
            }else{
                expanded = true;
                if(isIE6){
                    $("#utilities").css("width", "283px");
                    $("#utilities_options").show();
                }else{
                    $("#utilities").animate({marginRight:'0px'}, 'normal', 'swing');
                }
            }
        });
        if(!isIE6){
            $("#utilities").mouseenter(function(){
                if(expanded == false){
                    expandUtilities = window.setTimeout(function (){
                        expanded = true;
                        $("#utilities").animate({marginRight:'0px'}, 'normal', 'swing')
                    },1000); /*Time in ms before expanding after the mouseenter*/
                }else{
                    expanded = true;
                    if(closeTimeUtilities){window.clearTimeout(closeTimeUtilities);}
                    if(closeUtilities){window.clearTimeout(closeUtilities);}
                }
            });
            $("#utilities").mouseleave(function(){
                window.clearTimeout(expandUtilities);
                if(expanded){
                    closeTimeUtilities = window.setTimeout(function (){
                        expanded = false;
                        closeTimeUtilities = false;
                    },1000); /*Time in ms before being able to expand again after the mouseleave*/
                    closeUtilities = window.setTimeout(function (){
                        $("#utilities").animate({marginRight:utilities_marginright}, 'normal', 'swing');
                    },1000); /*Time in ms before closing after the mouseleave*/
                };        
            });
        }


    });