/// <reference path="jquery-1.3.2.js" />

var SFConfig = {'AppMode': {'Live': false, 'Edit': false, 'Preview': false}};

$(document).ready(function() {
    InitAppMode();
    $('.styleswitch').switcher();
    $('.clbc-Search input:first').inputLabel();
    InitContactPanel();
    $(".clbc-Accordion").accordion({
        active: false,
        collapsible: true,
        autoHeight: false
       });
	$('.clbc-Accordion2 h2').wrapInner('<a href="#" />').click(function() { // used on the 'Links' page (different to '.clbc-Accordion' because more than one section of the Accordion can be open at once). 
		$(this).next().slideToggle('slow');
		$(this).toggleClass('open')
		return false;
   		});
   	$('.clbc-Accordion2 h2[class!="open"]').next().hide();
	InitCollapsiblePanel();
    InitHeaderFlyout();
    InitNewNotableTabs();
    InitSearch();
    InitNewNotable();
    InitHeroLauncher();
    InitEditMode();
});


// Analytics event tracking (for outbound links and document downloads)
$(document).ready(function(){
	$('a').each(function(){
		var a=$(this);
		var href=a.attr('href');
		if(href==undefined)
			return;
		var url=href.replace('http://','').replace('https://','');
		var hrefArray=href.split('.').reverse();
		var extension=hrefArray[0].toLowerCase();
		var downloadTracked=false;
		var analyticsFileTypes = ['pdf','doc','docx','xls','xlsx','zip','ashx'];
		if($.inArray(extension,analyticsFileTypes)!=-1){
			downloadTracked=true;
			a.click(function(){
				_gaq.push(['_trackEvent','Downloads',extension.toUpperCase(),href]);
			});
		}
		if((href.match(/^http/))&&(!href.match(document.domain))&&(downloadTracked==false)){
			a.click(function(){
				_gaq.push(['_trackEvent','Outbound Traffic',href.match(/:\/\/(.[^/]+)/)[1],href]);
			});
		}
	});
});


InitEditMode = function() {

    $(".clbc-EditMode").parent().css("background-position", "0 78px");
    $(".clbc-EditMode").parent().css("background", "none");

    // IE7 bug issues
    /*
    $(".clbc-EditMode .overlay").each(function(i) {
        //$(this).css("margin-left", "-200px");
        var l = $(this).css("left").replace("px", "") - 200;
        $(this).css("left", l + "px");

    });
    */
}


InitHeroLauncher = function() {
    // Allow logged-in user to hide or reveal content switcher

    //heroVisible = ($('.clbc-Hero-Promo-Hidden').length > 0) ? false : true;
    var heroVisible = HeroVisible();

    $('.clbc-Hero-Launcher').toggle(
        function() {
            HeroLauncherShow(!heroVisible);
            HeroVisible(!heroVisible);
            $.getJSON("/clbc/services/ContentSwitcherHandler.ashx?CntSwitcherHidden=" + heroVisible, function(result) { });
        },
        function() {
            HeroLauncherShow(heroVisible);
            HeroVisible(heroVisible);
            $.getJSON("/clbc/services/ContentSwitcherHandler.ashx?CntSwitcherHidden=" + !heroVisible, function(result) { });
        }
    );
}

HeroVisible = function(show) {
    if (show != null) {
        $.cookie('clbc-HeroVisible', show, { expires: 30 });
    }
    else {
        return ($.cookie('clbc-HeroVisible') != null) ? Boolean($.cookie('clbc-HeroVisible') == 'true') : (!$('.clbc-Hero-Promo-Hidden').length > 0);
    }
}

HeroLauncherShow = function(show)
{
    if (show){
        $(".clbc-Hero-Promo").slideToggle("slow");
        $(".clbc-Hero-Launcher").removeClass("hidden");
        $(".clbc-Hero-Launcher a").text("Hide");
    }
    else{
        $(".clbc-Hero-Promo").slideToggle("slow");
        $(".clbc-Hero-Launcher").addClass("hidden");
        $(".clbc-Hero-Launcher a").text("Reveal");
    }
}


InitSearch = function() {

    // Tabs for main content placement
    $(".clbc-Content1 .clbc-SearchContainer").tabs().tabs('select', 0);

    // Tabs for "Refine Search"
    $(".clbc-RefineSearch .clbc-SearchContainer").tabs().tabs('select', 0);

    // Replace "Advanced Search" link
    $('.clbc-Content2 .clbc-SearchPanel .clbc-ButtonAdvancedSearch').attr("href", "/search.aspx?Advanced=True");
}

InitNewNotable = function() {

    // Tabs for main content placement
    $(".clbc-Content1 .clbc-NewNotableMenu").tabs().tabs('select', 0);

   
}


InitNewNotableTabs = function() {
    $(".clbc-RotationPanel.loggedIn .clbc-PanelContent").tabs();
}


InitHeaderFlyout = function() {

    // Header flyout, such as those found on the Links result pages
    $(".clbc-HeaderFlyout .clbc-ButtonFlyout").toggle(
        function() {
            $(".clbc-HeaderFlyout .clbc-HeaderFlyoutContent").slideToggle("slow");
            $(this).parent().addClass("expanded");
        },
        function() {
            $(".clbc-HeaderFlyout .clbc-HeaderFlyoutContent").slideToggle("slow");
            $(this).parent().removeClass("expanded");
        });

}

InitCollapsiblePanel = function()
{
    $(".clbc-CollapsiblePanelContent").each(function()
    {
        var $this = $(this);
        if ($(':checkbox:checked', $this).length > 0)
        {
            $this.show().parent().addClass("expanded");
        }
    });
    
    // Collapsible panel, such as those found on the Links result pages
    $(".clbc-ViewAll").toggle(
        function()
        {
            var $this = $(this);
            var $panels = $(".clbc-CollapsiblePanel", $this.parent());
            $panels.each(function()
            {
                var $currPanel = $(this);       
                if (!$currPanel.hasClass("expanded"))
                {
                    $currPanel.addClass("expanded");
                    $(".clbc-CollapsiblePanelContent", $currPanel).slideToggle("slow");
                }
            });
            
            $this.text("Hide All").attr("title", "Hide All");
        },
        function()
        {
            var $this = $(this);
            var $panels = $(".clbc-CollapsiblePanel", $this.parent());
            $panels.each(function()
            {
                var $currPanel = $(this);
                if ($currPanel.hasClass("expanded"))
                {
                    $currPanel.removeClass("expanded");
                    $(".clbc-CollapsiblePanelContent", $currPanel).slideToggle("slow");
                }
            });

            $this.text("View All").attr("title", "View All");
        });

    $(".clbc-CollapsiblePanelHeader").click(function()
    {
        var $this = $(this);
        var $parent = $this.parent();
        $this.next().slideToggle("slow");

        if ($parent && $parent.hasClass("expanded"))
        {
            $parent.removeClass("expanded");
        } else if ($parent)
        {
            $parent.addClass("expanded");
        }
    });


}

InitContactPanel = function() {

    // Generate contact panel menu click events
    $('.clbc-Content .clbc-ContentMenu a').click(function() {
        var $this = $(this);
        if ($this.parent().hasClass('clbc-Facebook') == false) {
            ContactPanelMenu($this);
            return false;
        }
    });

    // Display default information
    var $default = $('.clbc-Content .clbc-ContentMenu a.selected');
    var location = $.getURLParameter($default.attr("href"), 'LibId');

    if ($default.hasClass('general')) {
        // Retrieve general info
        ContactPanelDisplayGeneral(location);
    } else {
        // Retrieve location
        ContactPanelDisplayLocation(location);
    }

    InitContactPanelHours();


    $('.clbc-ContactPanel a.clbc-Launcher').click(function(evt) {
        $(this).toggleClass('selected');


        $('.clbc-ContactPanel .clbc-Content').slideToggle();
        evt.stopPropagation();
    });

    $('.clbc-ContactPanel .clbc-Content').click(function(evt) {
        evt.stopPropagation();
    });

    $('.clbc-CloseContact').click(function() {
        $('.clbc-ContactPanel .clbc-Content').slideUp();
        $('.clbc-ContactPanel a.clbc-Launcher').removeClass('selected');
    });

    $(document).click(function() {
        $('.clbc-ContactPanel .clbc-Content').slideUp();
        $('.clbc-ContactPanel a.clbc-Launcher').removeClass('selected');
    });
}

ContactPanelMenu = function($anchor) {

    // Select the link, unselect the rest
    $('.clbc-ContactPanel .clbc-ContentMenu a').removeClass('selected');
    $anchor.addClass('selected');

    var location = $.getURLParameter($anchor.attr("href"), 'LibId');
    
    // Check if it's "General" or
    if ($anchor.hasClass('general')) {

        // Retrieve general info
        ContactPanelDisplayGeneral(location);

    } else {

        // Retrieve location
        ContactPanelDisplayLocation(location);
    }
}

ContactPanelDisplayGeneral = function(location) {

	// Display General Info
	$.getJSON("/clbc/services/libraryhandler.ashx?libid=" + location, function(data) {
        $('#clbcGeneral').hide();
		$("#clbcGeneral h2").html(data[0].Name);
		$("#clbcGeneral .phone_1").html(data[0].Phone);
		$("#clbcGeneral .ext").html(data[0].Extension);
		$("#clbcGeneral .phone_2").html(data[0].Phone2);
		$("#clbcGeneral .tollfree").html(data[0].TollFree);
		$("#clbcGeneral .email").attr("href", "mailto:" + data[0].Email).text(data[0].Email);
		
		if (data[0].Fax != null) {
			$("#clbcGeneral .fax_container").show();
			$("#clbcGeneral .fax").html(data[0].Fax);
		}
		else {
			$("#clbcGeneral .fax_container").hide();
			//$("#clbcGeneral .fax").html(data[0].Fax);
		}
		
        $('#clbcGeneral').slideDown('slow');
	});

	// Show General Info display
	$('#clbcLocation').hide();
	$('#clbcGeneral').show();
}

ContactPanelDisplayLocation = function(location) {

    // Display the location's info
    $.getJSON("/clbc/services/libraryhandler.ashx?libid=" + location, function(data) {
        $('#clbcLocation').hide();
        $('#clbcLocation .name a').html(data[0].Name);
        $('#clbcLocation a.url').attr("href", data[0].Url + "?libid=" + location);
        $('#clbcLocation a.id').attr("href", data[0].Id);
        if (data[0].Image != null) {
            $('#clbcLocation .image').show();
        } else {
            $('#clbcLocation .image').attr("src", data[0].Image);
            $('#clbcLocation .image').attr("alt", data[0].Name);
        }
        $('#clbcLocation .address_1').html(data[0].Address);
        $('#clbcLocation .address_2').html(data[0].Address2);
        $('#clbcLocation .phone_1').html(data[0].Phone);
        $('#clbcLocation .phone_2').html(data[0].Phone2);

//        if (data[0].Extension != null) {
//        	$("#clbcLocation .ext_container").show();
//        	$("#clbcLocation .ext").html(data[0].Extension);
//        }
//        else {
//        	$("#clbcLocation .ext_container").hide();
//        }
        
        if (data[0].TollFree != null) {
        	$("#clbcLocation .tollfree_container").show();
        	$("#clbcLocation .tollfree").html(data[0].TollFree);
        }
        else {
        	$("#clbcLocation .tollfree_container").hide();

        }
  
        if (data[0].Fax != null) {
        	$("#clbcLocation .fax_container").show();
        	$("#clbcLocation .fax").html(data[0].Fax);
        }
        else {
        	$("#clbcLocation .fax_container").hide();
        }
      
        if (data[0].Email != null) {
        	$("#clbcLocation .email_container").show();
        	$("#clbcLocation .email").attr("href", "mailto:" + data[0].Email).text(data[0].Email);
        }
        else {
        	$("#clbcLocation .email_container").hide();
        }
       
     
        $('.clbc-ContactPanel .clbc-ContentDisplay .hours .hours_data ul').html(data[0].Hours);
        $('#clbcLocation .id').attr("href", "/clbc/services/FavouriteBranchHandler.ashx?LibId=" + data[0].Id);

        $('#clbcLocation').slideDown('slow');
    });

    // Set branch as favourite
    $('#clbcLocation .clbc-SetLocalBranch').unbind('click').click(function() {
        var faveId = $.getURLParameter($(this).attr("href"), 'LibId');
        alert("You have selected a new favorite location.\n\nTHIS FUNCTIONALITY HAS NOT BEEN IMPLEMENTED!"); // YET TO BE IMPLEMENTED
        return false;
    });

    // Show Location Info display
    $('#clbcGeneral').hide();
    $('#clbcLocation').show();
}

InitContactPanelHours = function() {
    $('.clbc-ContactPanel .clbc-ViewHours').click(function() {
        $(this).toggleClass('selected');
        $('.clbc-ContactPanel .clbc-ContentDisplay .hours').toggleClass('visible');
    });

    $('.clbc-ContactPanel .clbc-Close').click(function() {
        $('.clbc-ContactPanel .clbc-ViewHours').removeClass('selected');
        $('.clbc-ContactPanel .clbc-ContentDisplay .hours').toggleClass('visible');
    });
}

InitAppMode = function() {
    if ($('.clbc-EditMode').length >= 1)
        SFConfig.AppMode.Edit = true;
    else if ($('.clbc-PreviewMode').length >= 1)
        SFConfig.AppMode.Preview = true;
    else
        SFConfig.AppMode.Live = true;
}


