﻿//LAST REVISED APRIL 18TH 2011 -- TO ACCOMODATE FIXES TO HOMEPAGE (THAT BEN CHANGED)

//selectors
var TopSectionsSelector = ".section";
var SectionContentSelector = ".sectionContent";
var MiddleContentSelector = ".content .inner";
var strategicPriorityContentSelector= ".strategicPriorityContent";
var CurrentStrategicPriorityIndex = 1;
var StrategicPriorityKeyPrefix = "StrategicPriority";
var AutoTransitionDisabled=false;
var StrategicPriorityDataItems; 
var TabListDataItems;
var AdListDataItems;
var SelectedSectionId;
var AdItemWidth = 195;
var AdItemDisplayLimit = 5;
var AdItemDisplayCounter = 5;

//executes on document load
function pagePreLoad() {
     
	//preload images
    var pic1= new Image(100,25);
     pic1.src="../images/priority1.jpg";
    var pic2= new Image(100,25);
     pic1.src="../images/priority2.jpg";
    var pic3= new Image(100,25);
     pic3.src="../images/priority3.jpg";
    var pic4= new Image(100,25);
     pic4.src="../images/priority4.jpg";
    var pic5= new Image(100,25);
     pic5.src="../images/priority5.jpg";

    InitializeBottomAdTable();
     
	LoadJson();
	DisplayRandomTitles();	

	    //click handler for strategic priorities
    $(".strategicPriority").click(HandleStrategicPriorityClick);        

   //attach event handlers    
    $(SectionContentSelector + " .close").click(HideCurrentSection);
    $(SectionContentSelector + " .close").hover(function(){ $(".close img").attr("src", "../images/closeButtonHighlight.png")},
    function(){ $(".close img").attr("src", "../images/closeButton.png")}
    );
    $(TopSectionsSelector).click(HandleSectionClick);
    // attach bottom ad slide click event
    $("img#homeAdPrev").click(HandleBottomAdSliderPreviousClick);
    $("img#homeAdNext").click(HandleBottomAdSliderNextClick);
    
    //if user hovers over the section tabs
    $(TopSectionsSelector).hover(
                 function() 
    			 {
    			    var sectionId=$(this).attr("id"); 
    			    HandleSectionHover(sectionId);
    			 }
    			 ,
                 function() 
    			 {
    			    var sectionId=$(this).attr("id"); 
    			    HandleSectionUnhover(sectionId);
    			 }

    			);    

}

function HandleBottomAdSliderPreviousClick() {

    // we want to ensure the table is not animating when we are fulfilling this event
    $animated = $("#bottomHomeAds table:animated");
    if ($animated.length){
    	return;
	}

    if (IsMoreAdPrevious()) {
        var newMarginLeft = GetIngegerValueFromCss("#bottomHomeAds table", "margin-left") + $("#bottomHomeAds").outerWidth();
        $("#bottomHomeAds table").animate({ marginLeft: newMarginLeft + "px" }, 1500, null, DetermineAdNavigationButtonVisibility);
        
        AdItemDisplayCounter = AdItemDisplayCounter - AdItemDisplayLimit;
    }
}

function GetIngegerValueFromCss(selector, property) {    
    return parseInt($(selector).css(property).replace("px", ""));
}

function IsMoreAdPrevious() {
    //calculate how much of the ad table remaining to show
    //var widthToBeDisplayed = $("#bottomHomeAds table").outerWidth() + GetIngegerValueFromCss("#bottomHomeAds table", "margin-left") - $("#bottomHomeAds").outerWidth();
    //if (GetIngegerValueFromCss("#bottomHomeAds table", "margin-left") < 0) {
        //return true;
    //}
    
    if (AdItemDisplayCounter - AdItemDisplayLimit == 0) {
    	return false;
    }
    //return false;
    return true;
}

//NEEDS FIX for IE
function IsMoreAdNext() {
    //calculate how much of the ad table remaining to show
    //var widthToBeDisplayed = $("#bottomHomeAds table").outerWidth() + GetIngegerValueFromCss("#bottomHomeAds table","margin-left") - $("#bottomHomeAds").outerWidth();
    
    //if (widthToBeDisplayed >= AdItemWidth) {
        //return true;
    //}
    
    if (AdItemDisplayCounter < $("#bottomHomeAds td").length) {
    	return true;
    }
    return false;
}

function HandleBottomAdSliderNextClick() {
    
    // we want to ensure the table is not animating when we are fulfilling this event
    $animated = $("#bottomHomeAds table:animated");
    if ($animated.length){
    	return;
	} 
    
    if (IsMoreAdNext()) {        
        var newMarginLeft = GetIngegerValueFromCss("#bottomHomeAds table", "margin-left") - $("#bottomHomeAds").outerWidth();        
        $("#bottomHomeAds table").animate({ marginLeft: newMarginLeft+ "px" }, 1500, null, DetermineAdNavigationButtonVisibility);
        AdItemDisplayCounter = AdItemDisplayCounter + AdItemDisplayLimit;

    }
}

function DetermineAdNavigationButtonVisibility() {
    //display the next previsou buttons only if items left to be displayed on the corresponding side
    if (IsMoreAdNext()) {
        $("#homeAdNext").show();
    }
    else {
        $("#homeAdNext").hide();
    }

    if (IsMoreAdPrevious()) {
        $("#homeAdPrev").show();
    }
    else {
        $("#homeAdPrev").hide();
    }
}

function InitializeBottomAdTable() {

    $("#bottomHomeAds table").css("width", ($("#bottomHomeAds td").length * AdItemWidth) + "px");
    $("#bottomHomeAds table").css("margin-left", 0)

    DetermineAdNavigationButtonVisibility();  
    
}   

//executes after page is completely loaded
function pageLoaded()
{
	//fix for IE6 flickering bug
	var ie = document.all;
	if(ie)
	{
		try 
		{
			document.execCommand("BackgroundImageCache", false, true);		
		} 
		catch(err) {}
	}
	
    ShowNextStrategicPrioprity();   
    window.setInterval(ShowNextStrategicPrioprity, 8000);

}

function DisplaRandomTitleForSection(sectionId)
{

      var randomnumber=Math.floor(Math.random()*3);
      var skip=0;

	     for(var i = 0; i < TabListDataItems.length ; i++) 
	     {
	     
			        if (TabListDataItems[i].TabDestination === sectionId) 
			        {
			        	if(skip===randomnumber)
			        	{
			              var Title = TabListDataItems[i].Title;
			  			  $("#" + sectionId + " p").text(Title);
			  			  break;
			  			}
			  			else
			  			{
			  			 skip++;
			  			}
			        }
		
	     }

}

//displays random Titles for different tabs on the top
function DisplayRandomTitles()
{
  DisplaRandomTitleForSection("Residents");
  DisplaRandomTitleForSection("Business");
  DisplaRandomTitleForSection("ArtsCultureTourism");
  DisplaRandomTitleForSection("CityHall");
  DisplaRandomTitleForSection("InfoCentre");
  
}
	

//deserialzes the JSON string from the hidden field
function LoadJson()
{
 	// Highlights Json 
	var hightlightsHiddenInput = $("#HomePageHighlightsListItems");
	var jsonText= hightlightsHiddenInput.val();
	StrategicPriorityDataItems= eval("(" + eval(jsonText) + ")");
	
    // set the values into the page
    var strategicImages = $(".strategicPriorityImage");
    for (i =0; i < strategicImages.length && i < StrategicPriorityDataItems.length; i++)
    {
	      var indexComma = StrategicPriorityDataItems[i].ImageLink.indexOf(",");
	      var url = StrategicPriorityDataItems[i].ImageLink.substring(0, indexComma);
	      strategicImages[i].src=url;
    }
    AdItemDisplayLimit =  StrategicPriorityDataItems.length;
    AdItemDisplayCounter =  StrategicPriorityDataItems.length;

	
	// Tab Items Json
	var tabsHiddenInput = $("#HomePageTabListItems");
	var jsonText= tabsHiddenInput .val();
	TabListDataItems= eval("(" + eval(jsonText) + ")");
	
	// Ad Items Json
	var adsHiddenInput = $("HomePageAdListItems");
	var jsonText = adsHiddenInput.val();
	AdListDataItems = eval("(" + eval(jsonText) + ")");

}

function HandleStrategicPriorityClick() {

	$(".sectionContent").fadeOut("slow");
    //get the id of the clicked strategic priority
    var clickedStrategicPriority = $(this).attr('id');
    AutoTransitionDisabled=true;
    ChangeStrategicPriority(clickedStrategicPriority);
}


// Change the strategic priority 
function ShowNextStrategicPrioprity() {

	if(AutoTransitionDisabled===true)
	{
	   return;
	}

    //get key from current index
    var key = StrategicPriorityKeyPrefix + CurrentStrategicPriorityIndex;

    ChangeStrategicPriority(key);
    CurrentStrategicPriorityIndex++;
    
    //when all strategic priotiry is displayed start again from beginin
    if (CurrentStrategicPriorityIndex == StrategicPriorityDataItems.length +1) {
        CurrentStrategicPriorityIndex = 1;
    }
}

//shows the specified strategic priority
function ShowStrategicPriority(key) {

	//change the image 
    var imageSource = $("#" + $("#" + key).attr('BackgroundImageControlId')).attr('src');        
    $(MiddleContentSelector).clone().hide().css({ backgroundImage: "url(" + imageSource + ")" }).appendTo(".content");
    
	
    $(MiddleContentSelector).fadeIn(1000,function() {ShowStrategicText(key)});

}

function ShowStrategicText(key)
{

    for (var i = 0; i < StrategicPriorityDataItems.length; i++) {

        //find the one we need to display
        if (StrategicPriorityDataItems[i].Key === (key)) {

            var Title = StrategicPriorityDataItems[i].Title;
            var Link = StrategicPriorityDataItems[i].Url;
            var Description = StrategicPriorityDataItems[i].ContentSummary;


            var html = "<p><a href='" + Link + "'>" + Title + "</a><br />" + Description + "</p>"                      

			$(".strategicPriorityContent .text").html(html);
            
            
        }

    }	

	  $(".strategicPriorityContent .text").show();
      $(".strategicPriorityContent .text").animate({"top":0},1000);
}

//changes the Strategic Priority by hiding the current one and showing the specified one.
function ChangeStrategicPriority(key) {

	$(".strategicPriority").each(function () {$(this).attr("src",$(this).attr("NormalImage"));  });
	//hightlight the strategic priority button
	$("#" + key).attr("src",$("#" + key).attr("HighlightImage"));
    //hide the current strategic priority first
    $(".strategicPriorityContent .text").stop(true,true);
	$(".strategicPriorityContent .text").fadeOut(1000);
    $(MiddleContentSelector).fadeOut(1000, function(){ $(".strategicPriorityContent .text").css("top",50); $(this).remove();});

    ShowStrategicPriority(key);
}

//executes when user hover overs to the different sections
function HandleSectionClick() {

    //don't do anything if the last selected section is clicked again
    var sectionId = $(this).attr('id');

    if ((sectionId === $(SectionContentSelector).attr("SectionId")) && 
                    ($(SectionContentSelector + ":visible").length>0)) {        
        return;
    }

    var elementClicked = this;
    ShowNewSection(elementClicked );

}


//handles the event when user hovers over to the section
function HandleSectionHover(sectionId)
{
  //unselect everything else than the hovered
  $(".section").not("#" + sectionId).children(".sectionTab").attr("src","../images/tabNormal.png");

  //change the sectionTab image of current section to show the selection
  $("#" + sectionId + " .sectionTab").attr("src","../images/tabSelected.png");
  

}

//handles the event when user unhovers from a section
function HandleSectionUnhover(sectionId)
{
 
   //if any section is shown, display the indent for it, hide rest   
  $(".section").not("#" + SelectedSectionId).children(".sectionTab").attr("src","../images/tabNormal.png");
  $("#" + SelectedSectionId + " .sectionTab").attr("src","../images/tabSelected.png");


}



function HideCurrentSection()
{
  //unselect everything on the top section tab
  $(".section .sectionTab").attr("src","../images/tabNormal.png");
  
	SelectedSectionId=null;	
	AutoTransitionDisabled=false;
    var sectionToHide=$(this).parents().filter(".sectionContent");
    sectionToHide.fadeOut("slow");    
}

//NOTE: this function is not needed anymore and should be deleted
// hides the current section and optionally displays another
function ChangeCurrentSection(elementHovered) {

    var overlayContent = $(SectionContentSelector);   
    
    ShowNewSection(elementHovered);
    
}


function ShowNewSection(elementHovered) {
	SelectedSectionId=$(elementHovered).attr("id");

	//reduce the z-index of all shown element 
	
	var shownOverlays= $(".sectionContent").css("z-index",3);

    var sectionContentId = $(elementHovered).attr('SectionContentId');
	
    var overlayContent = $("#" + sectionContentId );


    //overlay should have the same position and size as MiddleContent
    //overlayContent.width($(MiddleContentSelector).width());
    //overlayContent.height($(MiddleContentSelector).height());
    var middleContentOffset = $(MiddleContentSelector).offset();
    //overlayContent.css("left", middleContentOffset.left);
    //overlayContent.css("top", middleContentOffset.top);

    //increase the z-index of the overlayContent

   	overlayContent.css("z-index",4);

    //change the text of the MiddleContent
    //    $(SectionContentSelector + " .inner").text($(elementHovered).text());
    
    //change the section image
    var imageSource = $("#" + $(elementHovered).attr('BackgroundImageControlId')).attr('src');    
    overlayContent.css({ backgroundImage: "url(" + imageSource + ")" });

    var sectionId = $(elementHovered).attr('id');

    $(".sectionInner", overlayContent).empty();

    //add data from jquery
    for (var i = 0; i < TabListDataItems.length ; i++) {
        if (TabListDataItems[i].TabDestination === sectionId) {
            var Title = TabListDataItems[i].Title;
            var Link = TabListDataItems[i].Url;
            var Description = TabListDataItems[i].ContentSummary;            
            var html= "<p><a href='" + Link + "'>" + Title + "</a><br />" + Description + "</p>"
            $(" .sectionInner", overlayContent).append(html);
        }     
        
    }
    //move the clicked Title to the top 
    var priorityItem= $(" .sectionInner p a:contains('" +  $(" p", elementHovered).text() + "')", overlayContent);
    $(" .sectionInner", overlayContent).prepend(priorityItem.parent().eq(0));
    	
	//alert(overlayContent.css("display"));
    //show overlay by sliding down
    overlayContent.slideDown("slow", function(){HidePreviousSection(overlayContent.attr("id"));});

}

function HidePreviousSection(currentOverlayId)
{
	var shownOverlays= $(".sectionContent:visible");
	shownOverlays.each(
	function(){
		var eachOverlayId=$(this).attr("id");
		if(eachOverlayId !== currentOverlayId)
		{
		  $(this).hide();
		}
	}
	);
    
		
}



