/*
Copyright (c) 2011, ecentricarts Inc. All rights reserved.
*/


/**
* The CC module is the global namespace for Calcio Cottage 
* @module CC
*/
if (typeof CC == "undefined" || !CC) {
    var CC = {};
}

/**
* Utility methods and variables.
* @global util
*/
CC.util = {
    /**
    * Get root url for the site while managing different locations.
    * @method sitePath
    * @return {string} URL.
    */
    sitePath: function () {
        var url = document.location.protocol + '//' + document.location.host + '/';
        if (url.indexOf('192') > 0) {
            url += 'CalicoDev/';
        }
        return url;
    },
    /**
    * Get querystring parameter.
    * @method getParamByName
    * @return {string} value.
    */
    getParamByName: function (name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null)
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
};

/**
* UI methods and variables.
* @global UI
*/
CC.ui = {
    /**
    * Flag for having the login window open.
    * @property isOpen
    */
    isOpen: false,
    /**
    * URL to login page.
    * @property loginURL
    */
    loginURL: CC.util.sitePath() + "Modal/System/Login.aspx",
    /**
    * Length of a breadcrumb item.
    * @property breadcrumbItemLength
    */
    breadcrumbItemLength:150,
    /**
    * Open the login page.
    * @method openLogin
    */
    openLogin: function () {
        $.colorbox({
            href: CC.ui.loginURL,
            iframe: true,
            innerWidth: 610,
            innerHeight: 345,
            initialWidth: 550,
            initialHeight: 285,
            opacity: 0.4,
            scrolling: false,
            onOpen: function () { },
            onLoad: function () { $("#cboxWrapper").append('<div id="customerTreat"><img src="' + CC.util.sitePath() + 'calicocottage/images/imgLoginFudgeSmall.png" width="120" height="103" /></div>') },
            onComplete: function () { CC.ui.isOpen = true; },
            onCleanup: function () { $("#cboxWrapper").remove("#customerTreat"); },
            onClosed: function () { CC.ui.isOpen = false; }
        });
    },
    /**
    * Redirect from login.
    * @method redirect
    */
    redirect: function (path) {
        if (path == null) {

            var redirect = CC.util.getParamByName("ReturnUrl");
            if ((redirect != null) && (redirect != undefined) && (redirect != "")) {
                window.location = redirect;
            }
            else {
                window.location = window.location;
            }
        }
        else {
            window.location = path;
        }
    },
    /**
    * Show the login form.
    * @method showLoginForm
    */
    showLoginForm: function (loginID, reminderID) {
        $(loginID).removeClass('active').addClass('active');
        $(reminderID).removeClass('active');
    },
    /**
    * Show the password reminder form.
    * @method showReminderForm
    */
    showReminderForm: function (loginID, reminderID) {
        $(reminderID).removeClass('active').addClass('active');
        $(loginID).removeClass('active');
    },
    openLoginWhenReturnUrl: function () {
        var redirect = CC.util.getParamByName("ReturnUrl");
        if ((redirect != null) && (redirect != undefined) && (redirect != "")) {
            CC.ui.openLogin();
        }
    },
    /**
    * Manage the length of the breadcrumb.  Requires jquery.truncate.
    * @method manageBreadCrumbLength
    */
    manageBreadCrumbLength: function () {
        if ($('#breadCrumb span, #breadCrumb a').length > 0) {
            $('#breadCrumb span, #breadCrumb a').truncate({
                width: CC.ui.breadcrumbItemLength,
                after: '&hellip;',
                center: false,
                addclass: false,
                addtitle: false
            });       
        }
    }
};

/**
* Comment board methods and variables.
* @global member
*/
CC.comments = {
    /**
    * Slide open the commenting form.
    * @method open
    */
    isOpen: false,
    open: function () {
        var commentButton = $("#commentFormToggle a");
        commentButton.parent().parent().next(".expandable").animate({
            height: "toggle"
        }, 800, "easeOutSine", function () {
            commentButton.parent().parent().parent().toggleClass("active");
            if (commentButton.parent().parent().parent().hasClass("active")) {
                CC.comments.isOpen = true;
            }
            else {
                CC.comments.isOpen = false;
            }
        });
        return false;
    }
};


function popupPlugin(fileURL) {
    var windowPopup = CC.util.sitePath() + 'calicocottage/templates/VideoPopOut.aspx?file=' + fileURL;
	var windowName = "popupVideo";
	var windowSettings = "width=640,height=368,scrollbars=no,location=false,directories=false,toolbar=false,resizable=false";
	window.open(windowPopup, windowName, windowSettings);
	return false;
}

$(document).ready(function () {
	
    (function ($) {
        $.fn.hoverFix = function () {
            if (!$.browser.msie || $.browser.version != '6.0') {
                return;
            }
            this.hover(function () {
                $(this).addClass('hover');
            }, function () {
                $(this).removeClass('hover');
            });
        };
    })(jQuery);

    /* Global */
    $("#mainNav > li, #topNavAccountUser").hoverFix();
    $('ul li:last-child, .commentPosting:last-child').addClass('last');
    $('ul li:first-child').addClass('first');

    // Set Superfish animation values
    var menuAnimationStart = '103px';
    var menuAnimationEnd = '105px';
    var animation = { opacity: 'show', top: menuAnimationStart };
    var arrowAnimationStart = '-10px';
    var arrowAnimationEnd = '12px';
    // Replace fade with slide for IE6-8 for PNG support
    if (($.browser.msie && $.browser.version > 6 && $.browser.version <= 8)) { animation = { top: menuAnimationStart, height: 'show' }; }
    // Call Superfish plugin on main navigation	
    $("#mainNav").superfish({
        onInit: function () {
            $('>li:has(".navPanel")', this).each(function () {
                if (!$(this).hasClass("here")) $("span.arrow", this).css({ 'opacity': 0, 'bottom': arrowAnimationStart });
            });
        },
        onHide: function () {
            $(this).css({ 'top': menuAnimationEnd }).parent().each(function () { if (!$(this).hasClass("here")) $("span.arrow", this).stop().css({ 'opacity': 0, 'bottom': arrowAnimationStart }); });
        },
        onBeforeShow: function () {
            if (!$(this).parent().hasClass("here")) $("span.arrow", this.prev()).stop().css({ 'opacity': 0, 'bottom': arrowAnimationStart }).animate({ 'bottom': arrowAnimationEnd, 'opacity': 1 }, 700, "easeOutBack");
        },
        animation: animation
    });
    // Menu orphan items without superfish add hoverintent and custom animation
    $("span.arrow", $('#mainNav>li:not(:has(".navPanel"))')).css({ 'opacity': 0, 'bottom': arrowAnimationStart });
    $('#mainNav>li:not(:has(".navPanel"))').hoverIntent(
		function () { if (!$(this).hasClass("here")) $("span.arrow", this).css({ 'opacity': 0, 'bottom': arrowAnimationStart }).animate({ 'bottom': arrowAnimationEnd, 'opacity': 1 }, 700, "easeOutBack"); },
		function () { if (!$(this).hasClass("here")) $("span.arrow", this).stop().css({ 'opacity': 0, 'bottom': arrowAnimationStart }); }
	);

	// Print button
	$("#print a").live('click', function(event) {
		event.preventDefault();
		window.print();
		return false;
	 });
	 
	// Crossfade background image blends
    $("#homeLoginRegister a, .btnRegister, .btnLogin, .btnLearnMore").blend();

    $("#ctaAskCalicoSlider").css({"overflow":"hidden"}).sudoSlider({
        insertAfter: false,
        prevHtml: '<span class="arrow back"><a href="#">«</a></span>',
        nextHtml: '<span class="arrow forward"><a href="#">»</a></span>',
        controlsShow: true,
        controlsAttr: 'class="sliderControls"',
        continuous: true,
        autoheight: true,
        autowidth: true,
        ease: 'easeOutSine',
        beforeAniFunc: function (t) {
            $("#ctaAskAnswer").attr("href", $(this).children().attr('href'));
        }
    });

    $("#footerRelatedSlider").css({"overflow":"hidden"}).sudoSlider({
        autowidth: false,
        slideCount: 3,
        insertAfter: false,
        prevHtml: '<span class="arrow back"><a href="#">«</a></span>',
        nextHtml: '<span class="arrow forward"><a href="#">»</a></span>',
        controlsShow: true,
        controlsAttr: 'class="sliderControls"',
        continuous: false,
        ease: 'easeOutSine'
    });


	var homeAuto = true;
	var homeAutostopped = false;
    	var homeSlider = $("#homeBanner").css({"overflow":"hidden"}).sudoSlider({
        autowidth: false,
        autoheight: false,
        insertAfter: true,
        prevHtml: '<a id="btnPrev" href="#">«</a>',
        nextHtml: '<a id="btnNext" href="#">»</a>',
        controlsShow: true,
        controlsAttr: 'id="homeBannerButtons"',
        continuous: true,
        fade: true,
        ease: 'easeOutSine',
        pause: 5000,
        auto: true,
        resumePause: 15000

    }).mouseenter(function() {
	homeAuto = homeSlider.getValue('autoAnimation');
	if (homeAuto)
	{
		homeSlider.stopAuto();
	}
	else
	{
		homeAutostopped = true;
	}
	}).mouseleave(function() {
	if (!homeAutostopped)
	{
		homeSlider.startAuto();
	}
	});


    var loginbox = $(".login").colorbox({
        iframe: true,
        innerWidth: 610,
        innerHeight: 345,
        initialWidth: 550,
        initialHeight: 285,
        opacity: 0.4,
        scrolling: false,
        onOpen: function () { },
        onLoad: function () { $("#cboxWrapper").append('<div id="customerTreat"><img src="' + CC.util.sitePath() + 'calicocottage/images/imgLoginFudgeSmall.png" width="120" height="103" /></div>') },
        onComplete: function () { },
        onCleanup: function () { $("#cboxWrapper").remove("#customerTreat"); },
        onClosed: function () { }
    });

    if ($(".howtoStepPhoto a[rel='howto']").length > 0) {

        // How to magnify
        $(".howtoStepPhoto a[rel='howto']").prepend("<span></span>").colorbox({
            scalePhotos: true,
            maxWidth: "90%",
            maxHeight: "90%",
            opacity:0.4,
            photo: true
        });
    }

    if ($('.videoAsset').length > 0) {

        // Topic Landing video icons
        $('<div class="videoPlayIcon"><span></span></div>').appendTo($(".videoAsset")).each(function () {
            var img = $(this).prev();
            var margin = (($(img).outerWidth() - $(img).width()) / 2);
            $(this).parent().css({
                "width": $(img).outerWidth(),
                "height": $(img).outerHeight(),
                "display": "block"
            });
            $(this).css({
                "opacity": "0.6",
                "marginRight": margin + "px",
                "marginLeft": margin + "px",
                "marginTop": margin + "px",
                "marginBottom": margin + "px",
                "width": $(img).css('width'),
                "height": $(img).css('height')
            }).children().css({ "opacity": "0.3" });
        });
    }

	/*
		Main navigation search box label
	*/
	$('#searchBox').slidinglabels({
		className : 'searchTextBoxControl',
		topPosition : '14px',
		leftPosition : '7px',
		axis : 'x',
		speed : 300
	});

	/*
		Tooltips
	*/
    if ($('.contentRestricted h3 img').length > 0) {
        $('.contentRestricted h3 img').qtip({
            content: {
                attr: 'alt'
            },
            position: {
                my: 'bottom center',
                at: 'top center'
            },
            style: {
                tip: {
                    corner: 'bottom center'
                },
                classes: 'ui-tooltip-shadow'
            }

        });
    }

    $("#footerMenu li ul").each(function () {

        var width = $(this).width();
        var totalWidth = width;

        $("li", $(this)).each(function () {

            totalWidth -= $(this).outerWidth();

            if (totalWidth < 0) {
                $(this).addClass("newLine");
                totalWidth = width - $(this).outerWidth(true);
            }
        });
    });


    //If "RedirectURL" is present open login now.
    if (CC.ui.isOpen == false) {
        CC.ui.openLoginWhenReturnUrl();
    }

    //manage breadcrumbs
    CC.ui.manageBreadCrumbLength();

});
