var state = "home"; // State variable, equal to a web "page", default home
var lang = "en"; // Language variable, default English

function linkr(page,lg,mode){ // Function to initialise the page when the url changes
	$('.selecteditem').toggleClass('.selecteditem');
	if (page){state = page};
	if (lg){lang = lg};
	if (mode == "replace"){
		History.replaceState({"lang" : lang, "state" : state}, "Chow King & Associates: " + state, "/" + lang + "/" + state+ "/");
		_gaq.push(['_setAccount', 'UA-13300023-10']);
        _gaq.push(['_trackPageview', lang + '/' + state + "/"]);
	} else {
		History.pushState({"lang" : lang, "state" : state}, "Chow King & Associates: " + state, "/" + lang + "/" + state+ "/");
		_gaq.push(['_setAccount', 'UA-13300023-10']);
        _gaq.push(['_trackPageview', lang + '/' + state + "/"]);
	}
	menuSet(); 
	langbar();
	populate();
	return null;
	}

function menuSet(){ // Initialise the Menu
	$('.icon').each(function(index) {
		var passString = items.general.menu[lang];
			if (lang == "en") {
				passString = ["Home","About","Specialities","Credentials","Publications","Conferences","Services","Contact"]
			};
		$(this).replaceWith('<div class="icon">' + passString[index] +'</div>');
	});
}

function langbar(){ // Initialise the Language Bar
	if(lang == "en"){
		$('.iconlang').empty().append('<a href="#" onclick="linkr(state,\'zh-cn\'); return false;">简体中文</a><br><a href="#" onclick="linkr(state,\'zh-tw\'); return false;">繁體中文</a>');
	} else if (lang == "zh-cn") {
		$('.iconlang').empty().append('<a href="#" onclick="linkr(state,\'en\'); return false;">ENGLISH</a><br><a href="#" onclick="linkr(state,\'zh-tw\'); return false;">繁體中文</a>');
	} else if (lang == "zh-tw") {
		$('.iconlang').empty().append('<a href="#" onclick="linkr(state,\'en\'); return false;">ENGLISH</a><br><a href="#" onclick="linkr(state,\'zh-cn\'); return false;">简体中文</a>')
	}
}

function highlightSelected(item){ // Update the Highlighted Tab in the Navigation bar
	$('#nav li:nth-child(' + (item + 1) +') a .icon').toggleClass('selecteditem');
	if (item == 1){
	$("#banner").attr("src","/img/banners/2.jpg");
		$("#banners").addClass("eugene");
		$("#identity").addClass("eugeneLogo");
	} else {
		bannerSet(item+1);
	}
}

function bannerSet(img){ // Change the Banner for each state
	$("#banner").attr("src","/img/banners/" + img + ".jpg");
	$("#banners").removeClass("eugene");
}

function populate(){ // Populate the page with their respective content
	$('#content div').empty(); // Clear the page
	$('#content div').removeClass("dateList");
	$('#content div').removeClass("contactData");
	if(state == items.general.menu.en[0]){ // Home
		$('#content div').empty().append('<h2>'+ items[state][lang].caption + '</h2><p>' + items[state][lang].content + '</p>');
		highlightSelected(0);
		$('#content div').append('<h2>' + items.general.contentheader[lang][8] + '</h2><ul class="logoalbum"></ul>');
		for(var i=0; i<6; i++) { // 6 Logos
			$('ul.logoalbum').append($('<li><a href="' + items.general.affiliations[i] + '"><img src="/img/logos/' + i + '.png"/></a></li>'))}			
	} else if(state == items.general.menu.en[1]){ // About
		highlightSelected(1);
		$('#content div').append('<h2>' + items[state][lang].contentHeader + '</h2><p>'+ items[state][lang].content + '</p>');
		$('#content div').append('<h2>' + items[state][lang].listHeader + '</h2><ul id="fullList"></ul>');
		arraySet(1,1);
	} else if(state == items.general.menu.en[2]){ // Specialities
		arraySet(2);
		highlightSelected(2);
	} else if(state == items.general.menu.en[3]){ // Credentials
		highlightSelected(3);
		$('#content div').append('<h2>' + items[state][lang].contentHeader + '</h2><ul class="album"></ul>');
		for(var i=1; i<22; i++) { // Set the number of certificates you wish to display here by changing the 25 limiter.
			$('ul.album').append($('<li><a class="albumgroup" href="/img/credentials/' + i + '.jpg"><img src="/img/credentials/s/' + i + '.jpg"/></a></li>'))}
			$('.albumgroup').colorbox({ // Initialise the lightbox
				maxHeight:'90%',
				maxWidth:'90%',
				rel:'albumgroup'});
		$(document).bind('cbox_complete', function(){
    		setTimeout($('.cboxPhoto').protectImage(), 5000);
    		console.log("image loaded");
		});		
	} else if(state == items.general.menu.en[4]){ // Publications
		$('#content div').addClass("dateList");
		$('#content div').append('<h2>' + items.general.contentheader[lang][4] + '</h2>')
		arraySet(4);
		highlightSelected(4);
	} else if(state == items.general.menu.en[5]){ // Conferences
		$('#content div').addClass("dateList");
		$('#content div').append('<h2>' + items.general.contentheader[lang][5] + '</h2>')
		arraySet(5);
		highlightSelected(5);
	} else if(state == items.general.menu.en[6]){ // Services
		highlightSelected(6);
		var servicesHeader = items.general.contentheader[lang][6];
		$('#content div').append('<h2>' +servicesHeader+ '</h2><p>'+ items[state][lang] + '</p>');
	} else if(state == items.general.menu.en[7]){ // Contact
		highlightSelected(7);
		var contactHeader = items.general.menu[lang][7];
		if (lang =="en"){servicesHeader = "Contact Details"}
		var contactTerminology = items.general.terminology[lang];
		$('#content div').addClass("contactData");
		$('#content div').append('<h2>' + contactHeader + '</h2><p><span class="personalName">' + items.general.name[lang] + '</span><br><span class="companyName">' + items.general.company[lang] + '</span><br><span>' + items.general.address[lang] + '</span><br><br><span class="smallDetails">' +contactTerminology[1] + ': ' + items.general.phone + '</span><br><span class="smallDetails">' + contactTerminology[2] + ': '+ items.general.fax + '</span><br><span class="smallDetails">' +	contactTerminology[3] + ': <a href="mailto:' + items.general.email + '">' + items.general.email + '</a></span><br><span class="smallDetails">' + contactTerminology[4] + ': ' + items.general.site + '</span></p><h2>' + contactTerminology[0] + '</h2><p class="headedParagraph"></p>');
		$('#content div').append('<iframe class="googleMaps" width="976" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=30+Harbour+Road,+Wanchai&amp;aq=&amp;sll=22.307758,114.169235&amp;sspn=0.100529,0.099821&amp;vpsrc=6&amp;ie=UTF8&amp;hq=&amp;hnear=30+Harbour+Rd,+Hong+Kong&amp;t=m&amp;ll=22.280658,114.177797&amp;spn=0.007942,0.021458&amp;z=16&amp;output=embed"></iframe>');
	}
}

function arraySet(page,list){ // For more complex and repetitive content on pages, this is a special function which constructs the HTML for the page
	if(!list){var pivot = items[items.general.menu.en[page]]} else {var pivot = items[items.general.menu.en[page]][lang].items};
	$.each(pivot, function(intIndex, objValue){
		if (page == 1){
			$('#fullList').append($("<li>" + objValue + "</li>"));
		} else if (page == 2){
			$('#content div').append($("<h2>" + items.specialities[intIndex][lang].head + "</h2><p>" + items.specialities[intIndex][lang].content + "</p>"));
		} else if (page == 4){
			var branch = items.publications[intIndex][lang];
			if (branch.date){var buildDate = "<h3>" + branch.date + "<br>"} else {var buildDate = "<h3>"};
			if (branch.role){ var buildRole = "<strong>" + branch.role + "</strong></h3>"} else {var buildRole = "</h3>"};
			if (branch.body){ var buildBody = "<p><span class=\"body\">" + branch.body + "</span>"} else if (branch.title == null){var buildBody = "<p>"} else {var buildBody = ""};
			if (branch.title){ var buildTitle = "<p>\"<span class=\"title\">" + branch.title + "</span>\""} else {var buildTitle = ""};
			if (branch.leader){ var buildLeader = "<span class=\"leader\"> " + branch.leader + "</span>"} else {var buildLeader = ""};
			if (branch.publication){ var buildPublication = "<span class=\"publication\"> " + branch.publication + "</span>"} else {var buildPublication = ""};
			if (branch.comment){ var buildComment = "<span class=\"comment\"> [" + branch.comment + "]</span>"} else {var buildComment = ""};
			$('#content div').append(buildDate + buildRole + buildBody + buildTitle + buildLeader + buildPublication + buildComment);
		} else if (page == 5){
			var branch = items.conferences[intIndex][lang];
			if (branch.type == "2"){
				if (branch.date){var buildDate = "<h3>" + branch.date + "<br><strong>" + branch.location + "</strong></h3>"};
				if (branch.conference){var buildConference = "<p><span class=\"title\">" + branch.conference + "</span>"} else {buildConference = "<p>"};
				if (branch.title){var buildTitle = "<span class=\"talk\"> \"" + branch.title + "\"</span>"} else {buildTitle = ""};
				if (branch.title2){var buildTitle2 = "<span class=\"talk2\"> \"" + branch.title2 + "\"</span>"} else {buildTitle2 = ""};
				if (branch.body){var buildBody = "<span class=\"title\"> " + branch.body + "</span><br>"} else {buildBody = ""};
				if (branch.sponsor){var buildSponsor = "<span class=\"sponsor2\"> " + branch.sponsor + "</span></p>"} else {buildSponsor = "</p>"};
				if(branch.items != undefined){
					var buildItems = "<ul class=\"itemsList1\">";
					$.each(branch.items, function(intIndex, objValue){buildItems = buildItems + "<li>" + objValue + "</li>"});
					buildItems = buildItems + "</ul>";
				} else {var buildItems = ""};
				if(branch.items2 != undefined){
					var buildItems2 = "<ul class=\"itemsList\">";
					$.each(branch.items2, function(intIndex, objValue){buildItems2 = buildItems2 + "<li>" + objValue + "</li>"});
					buildItems2 = buildItems2 + "</ul>";
				} else {var buildItems2 = ""};
				$('#content div').append(buildDate + buildConference + buildTitle + buildBody + buildItems + buildTitle2 + buildItems2 + buildSponsor);
			} else {
			if (branch.date){var buildDate = "<h3>" + branch.date + "<br><strong>" + branch.location + "</strong></h3>"};
			if (branch.conference){var buildConference = "<p><span class=\"title\">" + branch.conference + "</span>"} else {buildConference = "<p>"};
			if (branch.title){var buildTitle = "<span class=\"talk\"> \"" + branch.title + "\"</span>"} else {buildTitle = ""};
			if (branch.body){var buildBody = "<span class=\"title\"> " + branch.body + "</span><br>"} else {buildBody = ""};
			if (branch.sponsor){var buildSponsor = "<span class=\"sponsor\"> " + branch.sponsor + "</span></p>"} else {buildSponsor = "</p>"};
			if(branch.items != undefined){
				var buildItems = "<ul class=\"itemsList\">";
				$.each(branch.items, function(intIndex, objValue){buildItems = buildItems + "<li>" + objValue + "</li>"});
				buildItems = buildItems + "</ul>";
			} else {var buildItems = ""};
			$('#content div').append(buildDate + buildConference + buildTitle + buildBody + buildSponsor + buildItems);
			}
		}
	});
};

// Tools

function getUrlVars() { // Checks the parameters passed behind a URL
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		vars[key] = value;
	});
	return vars;
}

// function protectImage(settings){
//   settings = jQuery.extend({
//     image: '/img/blank.gif',
//     zIndex: 10
//   }, settings);
//   return this.each(function() {
//     var position = $(this).position();
//     var height = $(this).height();
//     var width = $(this).width();
//     $('<img />').attr({
//       width: width,
//       height: height,
//       onclick: "$.colorbox.next();",
//       src: settings.image
//     }).css({
//       top: position.top,
//       left: position.left,
//       position: 'absolute',
//       zIndex: settings.zIndex
//     }).appendTo('#cboxLoadedContent')
//   });
// };

// OnLoad
$(document).ready(function(){ // When a page is loaded, do the following

	var History = window.History; // Setup History.JS
    if ( !History.enabled ) {return false;}

    History.Adapter.bind(window,'statechange',function(){
        var State = History.getState();
        console.log(State);
        lang = State.data.lang;
        state = State.data.state;
        linkr(state,lang,"replace");
    });

    $.getJSON("/data.json",function(data){ // Get the JSON data file with all the content
		items = data;
	if (document.location.search.charAt(0) === "?"){ // Check internal vs. external incoming link
			lang = getUrlVars()["lang"];
			state = getUrlVars()["state"];
			linkr(state,lang,"replace"); //If external, rewrite the URL without redirecting the user.
		} else {
			populate(); // Start building up the page
		}
	});
})
