var homeID = 5;
var curhash = '';
var curID = 0;
var imgInt = 0;
var imgbgInt = 0;
var imgbgCur = 0;
var imgbgCCount = 0;
var imgCount = 0;
var imgCur = 0;
var tpanelCount = 0;
var tpanelclick = 0;
var urlInt = 0;
var firstload = 1;
// IE text loading bug
(function($) {
    $.fn.customFadeIn = function(speed, callback) {
        $(this).fadeIn(speed, function() {
                if(jQuery.browser.msie)
                        $(this).get(0).style.removeAttribute('filter');
                if(callback != undefined)
                        callback();
        });
    };
    $.fn.customFadeOut = function(speed, callback) {
        $(this).fadeOut(speed, function() {
                if(jQuery.browser.msie)
                        $(this).get(0).style.removeAttribute('filter');
                if(callback != undefined)
                        callback();
        });
    };
})(jQuery);
//verification functions
function trimStr (str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function validatePhone(fld) {
    var error = "";
    var stripped = fld.replace(/[\(\)\.\-\ ]/g, '');    

	if (isNaN(parseInt(stripped))) {
        error = "invalid";
    }
    return error;
}
//loader
function loadContent(id,slug){

	$('#preloader').show();	
	dropImgTimers();
	$('#content').animate({
		opacity: 0
	}, 300, function() {
		$.ajax({
			type: "POST",
			url: templatedirectory+'/npage.php',
			data: "jsauth=wpgetdata&pageID="+id+"&pagepath="+slug+"&lang="+curLang,
			error: ["request failed"],
			success: function(data) {

				$('#content').html(data);
				imgbgCCount = $('#val_imgbg span').size();
				//switch page title
				var subtitle = $('#val_pagetitle').text();
				document.title = "Takumi  | "+subtitle;
				//images rotation
				imgCount = $('#content .imgpanel-1 .panelimg').size();	
				imgCur = 1;
				if(imgCount > 1) {
					$('#content .imgpanel-1 .panelimg').each(function(){
						if($(this).attr('id') != 'img1-1') {
							$(this).hide();
						}
					});
				}
				//create text buttons if any
				tpanelCount = $('#content .contentbody .tpanel').size();
				var contentdisplaytype = $('#val_contentdisplaytype').text();
				if(contentdisplaytype == 'scroll') {
					var templatetype = $('#val_templateversion').text();
					if(templatetype == '2') {
						var temptypeht = 480;
						if($('.imgpanel-2').size() > 0){
							temptypeht = 340;
							$('#contentscrolllimit').before('<div class="blockfiller"></div>');
						} 
							$('.contenttext').css('position','static');	
					
						if($('#contentscrolllimit').height() > temptypeht){
							$('#contentscrolllimit').css('height',temptypeht);
							//$('#contentscrolllimit').css('background','#333');
							$('#contentscrolllimit').css('overflow','auto');
							$('#contentscrolllimit').jScrollPane();
						}
					}
				} else if(contentdisplaytype == 'button') {
				if(tpanelCount > 1) {
					var tp = 0;
					var butappend = '';
					var ciroutimg = 'circle-out.png';
					if(imgbgCCount > 0){
						ciroutimg = 'circle-out2.png';
					} 
					$('#content .contentbody .tpanel').each(function(){
						tp++;
						$(this).attr('id','tp-'+tp);
						if(tp>1){
							$(this).hide();
							butappend += '<div class="textbut" id="bt-'+tp+'"><img src="'+templatedirectory+'/images/'+ciroutimg+'"></div>';
						} else {
							butappend += '<div class="textbut" id="bt-'+tp+'"><img src="'+templatedirectory+'/images/circle-over.png"></div>';
						}
						//create buttons
						
					});
					$('#content .contentbutton').html(butappend);
					tpanelclick = 1;
					//append evt states
					
					$('#content .contentbutton .textbut').hover(function(){
						$(this).children('img').attr('src',templatedirectory+'/images/circle-over.png');
					},function(){
						var pos = parseInt($(this).attr('id').split("-")[1],10);
						if(pos != tpanelclick){
							$(this).children('img').attr('src',templatedirectory+'/images/'+ciroutimg);
						}
					});
					$('#content .contentbutton .textbut').click(function() {
						var pos = parseInt($(this).attr('id').split("-")[1],10);
						if(pos != tpanelclick){
							if(tpanelclick != 0){
								$('#bt-'+tpanelclick+' img').attr('src',templatedirectory+'/images/'+ciroutimg);
								$('#tp-'+tpanelclick).hide();
							}
							$(this).children('img').attr('src',templatedirectory+'/images/circle-over.png');
							$('#tp-'+pos).fadeIn();
							tpanelclick = pos;
						}
					});
				}
				}
				//checking for val_imgbg
				
				$('#cp-bottombg').empty();
				if(imgbgCCount > 0) {
					if(!($('#navi-main').hasClass('naviwhite'))){
						$('#navi-main').addClass('naviwhite');
						$('#navi-sub').addClass('naviwhite');
						$('#content').addClass('shiftwhite');
						$('.navisub-title').addClass('shiftwhite');
					};
					$('#panel-widgets').fadeOut('fast');
					$('#logo').fadeOut('fast');
					$('#logobottom').fadeOut('fast');
					var imgapptext = "";
					var imgbgCC = 1;
					$('#val_imgbg span').each(function(){
						var nsrc = $(this).text();
						imgapptext += '<div class="bgpanel" id="imgbg-'+imgbgCC+'"><img src="'+nsrc+'"/></div>';
						imgbgCC++;
					});
					$('#cp-bottombg').html(imgapptext);
					$('#cp-bottombg .bgpanel').hide();
					$('#cp-bottombg #imgbg-1').fadeIn(500);
					imgbgCur = 1;
					
					initateBGTimer();
				} else {
					$('#navi-main').removeClass('naviwhite');
					$('#navi-sub').removeClass('naviwhite');
					$('#panel-widgets').removeClass('shiftwhite');
					$('#content').removeClass('shiftwhite');
					$('.navisub-title').removeClass('shiftwhite');
					$('#panel-widgets').fadeIn('fast');
					$('#logo').fadeIn('fast');
					$('#logobottom').fadeIn('fast');
				}
				
				//checking for webform
				if($('#content #regformpanel').size() > 0){
					$('#tf_date').datepicker({ dateFormat: 'dd/mm/yy' });
					$('#regformpanel #submit').click(function() {
						var formvalid = validateRegistration();
						if(formvalid == true) {
							submitRegistration();
						}
						return false;
					});
				}
				
				
				
				//animate content in
				
				$('#content').animate({
					opacity: 1
				}, 600, function() {
					$(this).show();
					if(jQuery.browser.msie) {
						$(this).get(0).style.removeAttribute('filter');
					 }
					if(imgCount > 1) {
						initateImgTimer();
					}
				});
				$('#preloader').hide();	
				curID = id;
				
				//checking for home
				if(id == homeID) {
					if($('#tickerroll').size() > 0){
						var tickerswitch = $('#tickerroll').html();
						//create ticker
						var nticker = '<div id="hometicker"><ul id="tickerscroll">'+tickerswitch+'</ul></div>';
						$('.imgpanel-1').append(nticker);
						$("ul#tickerscroll").liScroll(); 
					}
				
				}
				
				clearTimeout(urlInt);
				urlInt = setTimeout(checkURL,200);
			}
		});
	});	
}

function getpageID(url) {
	$.ajax({
			type: "POST",
			url: templatedirectory+'/ninicheck.php',
			data: "jsauth=wpgetdata&pagepath="+url+"&lang="+curLang,
			error: ["request failed"],
			success: function(data) {
				if(data == "404error"){
					//no such page
					rehash("");
					loadContent(5,"");
				} else {
					var pageID = data;
					$('#initialID').html(pageID);
					loadContent(pageID,"");
					if(url == "home/"){
						curhash = "";
					} else {
						curhash = "#/"+url;
					}
				}
				clearTimeout(urlInt);
				urlInt = setTimeout(checkURL,200);
			}
		});
}

//validation
validateRegistration = function(){
	$('#formerror').empty();
	var tfname = trimStr($('#tf_name').val());
	var tfcontact = trimStr($('#tf_contact').val());
	var tfemail = trimStr($('#tf_email').val());
	var tfdate = trimStr($('#tf_date').val());
	var tftimehr = $('#arrhr :selected').text();
	var tftimemin = $('#arrmin :selected').text();
	var tftime = $('#arrhr :selected').text()+":"+$('#arrmin :selected').text()+":00";
	var tfnoofppl = trimStr($('#tf_noofppl').val());
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	
	if(tfdate != "") {
		var tfswitch = tfdate.split("/");
		tfdate = tfswitch[1]+"/"+tfswitch[0]+"/"+tfswitch[2];
	}
	
	var aDate = new Date(tfdate);
	var today = new Date();
	var tdiff = aDate - today;
	
	if(tfname == ""){
		$('#formerror').html('Please fill in your name');
		return false;
	}
	if(tfcontact == ""){
		$('#formerror').html('Please fill in your contact number');
		return false;
	} else if(validatePhone(tfcontact) != "") {
		$('#formerror').html('Invalid contact number');
		return false;
	}
	if(tfemail == "") {
		$('#formerror').html('Please fill in your email');
		return false;
	} else if(!emailReg.test(tfemail)){
		$('#formerror').html('Invalid email');
		return false;
	}
	if(tfdate == ""){
		$('#formerror').html('Please enter your reservation date');
		return false;
	}
	if(tdiff < 0){
		$('#formerror').html('Reservation date cannot be earlier than today');
		return false;
	}
	if(tftimehr == "hr" || tftimemin == "min"){
		$('#formerror').html('Please enter your reservation time');
		return false;
	} else if(tftimehr != "hr" && tftimemin != "min"){
		//time to minutes
		var totalmin = (parseInt(tftimehr,10)*60)+parseInt(tftimemin,10);
		if(totalmin < 720 || (totalmin > 870 && totalmin < 1080) || totalmin > 1350) {
			$('#formerror').html('Reservation time is past opening hours');
			return false;
		}
	}
	if(tfnoofppl == ""){
		$('#formerror').html('Please fill in number of people attending');
		return false;
	}
	return true;
}

submitRegistration = function(){
	$('#formerror').empty();
	$('#formerror').html('Please wait while we submit your reservation.');
	$('#regformpanel #submit').hide();
	var tfname = trimStr($('#tf_name').val());
	var tfcontact = trimStr($('#tf_contact').val());
	var tfemail = trimStr($('#tf_email').val());
	var tfdate = trimStr($('#tf_date').val());
	var tftimehr = $('#arrhr :selected').text();
	var tftimemin = $('#arrmin :selected').text();
	var tftime = $('#arrhr :selected').text()+":"+$('#arrmin :selected').text()+":00";
	var tfnoofppl = trimStr($('#tf_noofppl').val());
	var tfseating = $('#choiceseat :selected').text();
	var tfoccasion = trimStr($('#tf_occasion').val());
	$.ajax({
			type: "POST",
			url: templatedirectory+'/regform.php',
			data: ({ 
				jsauth : "regformsubmit",
				name : tfname,
				contact : tfcontact,
				email : tfemail,
				date : tfdate,
				time : tftime,
				noofppl : tfnoofppl,
				choiceseat : tfseating,
				occasion : tfoccasion
			}),
			error: ["request failed"],
			success: function(data) {
				if(data == "submitted") {
					$('#regformpanel').empty();
					$('#regformpanel').html('<p>Thank you for your reservation. This is not a confirmation of your reservation. We will contact you again on your reservation status.</p>');
				}
			}
		});
}


function naviShift(id) {
	//alert(id);
	var affectedsub = $('#page-'+id).parent().parent().parent().attr('id');
	//	alert(affectedsub);
}

function rehash(newhash){
	window.location.hash = newhash;
	curhash = newhash;
}

function initiateEvents() {
	$('#navi-sub').hide();
	$('.navisubpanel').hide();
	$('.subclick').click(function(){
		var clickid = $(this).parent().attr('id').split("-")[2];
		
		$('.navisubpanel').hide();
		$('#navisub-'+clickid).show();
		$('#navi-main').stop().animate({
				opacity: 'toggle',
				left: '-146'
			}, 300, function() {
				//
		});
		//$('#navi-main').fadeOut();
		$('#navi-sub').stop().animate({
				opacity: 'toggle',
				left: '27'
			}, 400, function() {
				//
		});
		//$('#navi-sub').fadeIn();
		return false;
	});
	$('.link-switch').click(function(){
		var nid = $(this).attr('id').split("-")[1];
		var tohash = $(this).attr('href').split("#")[1];
		if(tohash == undefined) {
			//alert("tohash is undefined");
			//check secondary
			tohash = $(this).attr('href').replace(baseURL,"/");
		}
		if(tohash != curhash) {
			window.location.hash = tohash;
			//rehash(tohash);
			//loadContent(nid,"");
		}
		return false;
	});
	$('#logomainlink').click(function(){
		var nlink = $(this).attr('href')+"/home/";
		var tohash = "";
		if(tohash != curhash) {
			window.location.hash = tohash;
			//rehash(tohash);
			//loadContent(5,"");
		}
		return false;
	});

	$('.backtomain').click(function(){
		
		$('#navi-main').stop().animate({
				opacity: 'toggle',
				left: '27'
			}, 300, function() {
				//
		});
		
		$('#navi-sub').stop().animate({
				opacity: 'toggle',
				left: '146'
			}, 400, function() {
				$('.navisubpanel').hide();
		});
		return false;
	});
	//shift to id
}

//Timer scripts
dropImgTimers = function(){
	clearTimeout(imgInt);
}
initateImgTimer = function(){
	imgInt = setTimeout(imgSwitch,3000);
}

imgSwitch = function(){
	dropImgTimers();
	$('#content #img1-'+imgCur).animate({
		opacity: 'toggle'
	}, 1000, function() {
	});
	imgCur++;
	if(imgCur > imgCount){
		imgCur =1;
	}
	$('#content #img1-'+imgCur).animate({
		opacity: 'toggle'
	}, 1000, function() {
		initateImgTimer();
	});
}
dropBGTimers = function(){
	clearTimeout(imgbgInt);
}
initateBGTimer = function(){
	imgbgInt = setTimeout(imgbgSwitch,8000);
}

imgbgSwitch = function(){
	dropBGTimers();
	$('#cp-bottombg #imgbg-'+imgbgCur).animate({
		opacity: 'toggle'
	}, 1000, function() {
	});
	imgbgCur++;
	if(imgbgCur > imgbgCCount){
		imgbgCur =1;
	}
	$('#cp-bottombg #imgbg-'+imgbgCur).animate({
		opacity: 'toggle'
	}, 1000, function() {
		initateBGTimer();
	});
}
//checking URL
var gncount = 0;
checkURL = function(){
	gncount++;
	clearTimeout(urlInt);
	var curClientHash = window.location.hash;
	$('#fortesting').html(curClientHash+' : '+curhash + " : " + gncount);
	if(curClientHash == "#" && curhash == ""){
		curhash = "";
		curClientHash = "";
	}
	if(curClientHash == "" && curhash == "#/"){
		curhash = "";
		curClientHash = "";
		getpageID('home/');
		rehash("");
	} else if(curClientHash != curhash) {
		var url = curClientHash.replace("#/","");
		getpageID(url);
		rehash(curClientHash);
	}
	urlInt = setTimeout(checkURL,200);
}

$(function() {
	//
	if(isIE6 == false) {
	var ndisplace = $(window).height() - 650;
	if(ndisplace > 0){
		$('#header').css('padding-top',(ndisplace/2)-20);
	}
	//check initial links
	var curlink = window.location.href;
	if(curlink.charAt(curlink.length-1) != "/") {
		curlink += "/";
	}
	if(baseURL.charAt(baseURL.length-1) != "/") {
		baseURL += "/";
	}
	var nnhash = window.location.hash;
	if(curlink!= baseURL && nnhash == ""){
		//alert(baseURL);
		curlink = curlink.replace(baseURL,baseURL+"#/");
		window.location.href = curlink;
		//window.location.href = baseURL;
	} 
	//try loading
	if(nnhash != ""){
		nnhash = nnhash.replace("#/","");
		getpageID(nnhash);
	} else {
		var pageID = $('#initialID').html();
		
		loadContent(pageID,"");
		urlInt = setTimeout(checkURL,200);
	}
	if(firstload == 1){
		initiateEvents();
		firstload = 0;
	}
	} else {
		$('#wrapper').empty();
		$('html').css("background-image","none");
		$('#wrapper').html('<div id="ie6landing"><p><img src="'+templatedirectory+'/images/logoblack.jpg"/></p><p>&nbsp;</p><p>&nbsp;</p><p>This website is not optimized for Internet Explorer 6 and lower versions. Please <a href="http://www.microsoft.com/downloads/en/default.aspx" target="_blank">upgrade your browser</a>, thank you.</p></div>');
	}
});


