/**
 * common javascript functions
 *
 * @author Ethan Liu
 * @version $Id: functions.js 155 2009-09-24 09:36:29Z ethan $
 * @copyright Creativecrap.com, Ethan, 26 October, 2008
 * @package default
 **/

var l10n;
var sid;
// mm scripts
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
	newWin = window.open(theURL,winName,features);
	newWin.focus();
}

function popup(url, w, h, scrollbar) {
	var feature = 'toolbar=no,menubar=no,resizable=no,location=no,status=no';
	var left = Math.ceil((screen.width - w) / 2);
	var top = Math.ceil((screen.height - h) / 2);
	feature += ',scrollbars=' + scrollbar + ',width=' + w + ',height=' + h + ',top=' + top + ',left=' + left;
	setTimeout(function() {
		var popup = window.open(url, 'popup', feature);
	}, 500);
}

function redirect() {
	window.location = '/user/?redirect=' + window.location.href;
}

function nl2br(str) {
	var br = '<br />';
	return (str + '').replace(/([^>]?)\n/g, '$1'+ br +'\n');
}

function addslashes(str) {
	return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}


function validForm(form_id) {
	$(form_id + " :text,:password")
	.each(function() {
		var val = $.trim($(this).val());
		$(this).val(val);
		if (val == $(this).attr("rel")) {
			//$(this).val($(this).attr('rel')).removeClass('uniform-placeholder');
			$(this).val("").removeClass('uniform-placeholder');
		}
	});
	// check require fields
	var valid = true;
	$(form_id + " .require").each(function() {
		$(this).removeClass("uniform-form-invalid");
		//if ($(this).val() == "" || $(this).val() == $(this).attr("rel")) {
		if ($(this).val() == "") {
			$(this).addClass("uniform-form-invalid");
			valid = false;
		};
	});
	if (!valid) {
		$(form_id).uniform();
	};
	//$("#" + form_id + " .x-form-invalid:first").focus();
	//$("#" + form_id + " .x-form-invalid:first").trigger('click');
	return valid;
}

function t(str) {
	if (l10n) {
		var key = str.toLowerCase();
		str = l10n[key] ? l10n[key] : str;
	};
	return str;
}

function loadThumb(id, src, name) {
	var thumb = new Image();
	$(thumb).load(function() {
		var img = $("<img>").attr('src', src).attr('alt', name);
		var me = $("div.img[rel="+id+"]");
		me.wrapInner('<div class="desc"></div>').prepend(img).show();
	}).attr('src', src);
	return false;
}

function loadThumbTag(f) {
	$("div.img").hide();
	$("div.img").each(function() {
		var id = $(this).attr('rel');
		if (f[id]) {
			loadThumb(id, f[id]['path'], name);
		}
	});
}

function printer() {
	setTimeout(function() {
		window.print();
	}, 800);
}

function intval(num) {
	//num = $.trim(num);
	num = parseInt(num, 10);
	if (/\D/.test(num)) {
		return 0;
	}
	return num;
}

var newReleased = 0;
$(function() {
	$("#login-form").uniform({callback: function(result, status) {
		if (result.success) {
			if (result.redirect) {
				window.location = result.redirect;
			}
			else {
				window.location.reload();
			}
		}
	}});
	
	$("#cart-form").uniform({
		prepend: function() {
			var s = '';
			if ($("#seats-box").length) {
				if ($("#seats-box input[type=checkbox]:checked").length == 0) {
					$("#cart-form").uniformMsg({msg: t('Choose seat first')});
					return false;
				};
				$("#cart-form input[name='qt']").val($("#seats-box input[type=checkbox]:checked").length);
				/*
				var booking = $("#seats-box td.active");
				if (!booking.length) {
					$("#cart-form").uniformMsg({msg: t('Choose seat first')});
					return false;
				};
				booking.each(function(i, item) {
					s += $(item).attr('rel') + ",";
				});
				*/
			}
			//$("#cart-form [name='tickets']").val(s);
		},
		callback: function(result) {
			if (result.success) {
				if (result.redirect!="") {
					window.location = result.redirect;
				}
				else {
					reloadBasketList();
				}
			};
		}
	});

	$("#storeconfirmform").uniform({callback:function(result) {
		if (result.success) {
			$("body").append(result.data);
			$("#scfbutton").addClass('hide');
			$("#scfmessage").removeClass('hide');
			$("#storetransform").submit();
			//console.info('go transaction');
		}
		else {
			setTimeout(function() {
				//window.location = "/store/basket?sid=" + sid;
				window.location = result.redirect;
				//console.info('redirect: ' + result.redirect);
			}, 3000);
		}
	}});
	
	if ($("#newreleased-block").length) {
		$("#newreleased-block div.arrow.right").click(function() {
			var totalVisible = parseInt($("#newreleased-block").attr('rel'), 10);
			var newReleasedOffset = totalVisible - 1;
			if ((newReleased + newReleasedOffset) <= ($("#newreleased li").length - totalVisible)) {
				newReleased += newReleasedOffset;
			}
			else {
				newReleased += $("#newreleased li").length - 1 - newReleasedOffset - newReleased;
			}
			$("#newreleased").animate({marginLeft: (- 1 * newReleased * 130) + 'px'}, 'slow');
		});
		$("#newreleased-block div.arrow.left").click(function() {
			var totalVisible = parseInt($("#newreleased-block").attr('rel'), 10);
			var newReleasedOffset = totalVisible - 1;
			if ((newReleased - newReleasedOffset) >= 0) {
				newReleased -= newReleasedOffset;
			}
			else {
				newReleased = 0;
			}
			$("#newreleased").animate({marginLeft: (-1 * newReleased * 130) + 'px'}, 'slow');
		});
	};
	
	$("#storeSearchForm").uniform({
		prepend: function() {
			$("#search-buttom").addClass('disable');
			var url = "/store/search?search=" + escape($("#search-keyword-box").val()) + "&target=" + $("#target").val() + "&category=" + $("#category").val();
			$("#searchresult").load(url + " #searchresult", function() {
				$("#search-buttom").removeClass('disable');
			});
			return false;
		}
	});
	
	
	slideshow();
	$("form").uniform();

	/*
	if ($("a.fancybox").length) {
		$("a.fancybox").fancybox({
			'titleShow': true,
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic',
			'titlePosition': 'over',
			'titleFormat': function(title, currentArray, currentIndex, currentOpts) {
				return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
			}
		});
	};
	*/
	
	if ($("a.fancybox").length) {
		 $('#gallery a').lightBox();
	};
	
	var highlight = URLDecode($.getURLParam('highlight')).split(' ');
	if (highlight.length>0) {
		$("#content-wrapper").highlight(highlight, {wordsOnly:false});
	};
    /*
	//swfobject.switchOffAutoHideShow();
	//$.ui.dialog.defaults.bgiframe = true;
	$("#sblogin-form").uniform({callback: function(result, status) {
		if (result.success) {
			if (result.cmd == 'redirect') {
				window.location.href = result.data;
			}
			else {
				window.location.reload();
			}
		}
	}});
	$("#sbsearch-form").uniform();
	//$("input[name='dummy_channel']").css('width', 80);
	//$("#login-box").bgiframe();
	//swfobject.embedSWF("/images/pmenu.swf", "nav-lite", "990", "117", "9.0.0", {}, {"menu":false}, {"wmode":"transparent"});
	//$('#dialog').dialog({ autoOpen: false });
	*/
})

function slideshow() {
	var len = $(".slides-wrapper .slides-pager li").length;
	if (!len) {
		return;
	};
	$(".slides-wrapper .slides-pager li").click(function() {
		var id = $(this).attr('rel');
		$(".slides-wrapper .slides-pager li.visible").removeClass('visible');
		$(".slides-wrapper .slides-box li.visible").removeClass('visible');
		//if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)||/Chrome\/(\d+\.\d+)/.test(navigator.userAgent)) {
		//	$(".slides-wrapper .slides-box li.html").fadeOut();
		//}
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
			$(".slides-wrapper .slides-box .slide-entry").hide();
		}
		$(".slides-wrapper .slides-box .slide-entry.visible").removeClass('visible');
		$(this).addClass('visible');
		$(".slides-wrapper .slides-box [rel='" + id + "']").addClass('visible');
		//if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)||/Chrome\/(\d+\.\d+)/.test(navigator.userAgent)) {
		//	//$(".slides-wrapper .slides-box [rel='" + id + "']").show();
		//}
		
		setTimeout(function() {
			if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
				$(".slides-wrapper .slides-box .slide-entry").hide();
				$(".slides-wrapper .slides-box [rel='" + id + "'] .slide-entry").show();
			}
			$(".slides-wrapper .slides-box [rel='" + id + "'] .slide-entry").addClass('visible');
		}, 500);
	});
	$(".slides-wrapper .slides-pager li").mouseover(function() {
		$(this).click();
	});
	$(".slides-wrapper .slides-pager li:first").click();
	if (len > 1) {
		//$(".slides-wrapper .slides-box [rel='slide0']").addClass('visible');
		//$(".slides-wrapper .slides-box [rel='slide0']").addClass('visible');
		$(".slides-wrapper .slides-pager").show();
	};
}

function drawSeats(pos1, pos2, offset, direction, max) {
	if (!$("#seats-box").length) {
		return;
	};
	$("#seats-box").html('').hide();
	if (pos1[0]<1||pos1[1]<1||pos2[0]<1||pos2[1]<1||offset<1) {
		return false;
	};
	var table = $("<table width='100%' border='0' cellspacing='1' cellpadding='0' />");
	if (direction == 1) {
		//odd
		for (var y=pos1[1]; y <= pos2[1]; y++) {
			var box = $("<tr />");
			var dd = $("<td />").text(y+t('Row')).addClass('th_col');
			$(box).append(dd);
			for (var x=pos2[0]; x >= pos1[0]; x-=offset) {
				var value = y+'-'+x;
				var dd = $("<td />").text(x).addClass('seat').attr('rel', value);
				//var dd = $("<td />").text(value).addClass('seat-'+value);
				$(box).append(dd);
			};
			//$("#seats-box").append(box);
			$(table).append(box);
		};
	}
	else {
		//even
		for (var y=pos1[1]; y <= pos2[1]; y++) {
			var box = $("<tr />");
			var dd = $("<td />").text(y+t('Row')).addClass('th_col');
			$(box).append(dd);
			for (var x=pos1[0]; x <= pos2[0]; x+=offset) {
				var value = y+'-'+x;
				var dd = $("<td />").text(x).addClass('seat').attr('rel', value);
				//var dd = $("<td />").text(value).addClass('seat-'+value);
				$(box).append(dd);
			};
			//$("#seats-box").append(box);
			$(table).append(box);
		};
	}
	$("#seats-box").append(table);
	var w = intval((100/$("#seats-box table tr:first td").length) * Math.pow(10,2) + 0.5) / Math.pow(10,2);
	$("#seats-box td").css('width', w + '%');

	//$("#seats-box td").hover(mouseenter, mouseleave);
	$("#seats-box td").click(function() {
		if ($(this).is('.active')) {
			$(this).removeClass('active');
		}
		else if ($("#seats-box td.active").length < max) {
			$(this).addClass('active');
		};
	});
	
	$("#seats-box tr").hover(
		function() {
			$(this).find("td:first").addClass('hover');
		},
		function() {
			$(this).find("td:first").removeClass('hover');
		}
	);

	$("#seats-box td.th_col").unbind('click').unbind('mouseenter').unbind('mouseleave');
	$(disable_seats).each(function(i, item) {
		$("#seats-box td.seat[rel='" + item.seat + "']").addClass('disable').unbind('click').unbind('mouseenter').unbind('mouseleave');
		//$("#seats-box td.seat-" + item.seat).addClass('disable').unbind('click').unbind('mouseenter').unbind('mouseleave');
	});
	for (var i=0; i < seats_in_basket.length; i++) {
		$("#seats-box td.seat[rel='" + seats_in_basket[i] + "']").addClass('active');
	};
	$("#seats-box").show();
}

function fbLogin(url) {
	$.post('/user/signin?facebook', function(result) {
		if (result.success) {
			if (url.length) {
				window.location = url;
			}
			else {
				window.location.reload();
				location.href = 'user/?login';    // 2011-10-27 by tigercat
			}
		};
	}, 'json');
}

/* Copyright (c) 2006 Mathias Bank (http://www.mathias-bank.de)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * Thanks to Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
 */
jQuery.extend({
/**
* Returns get parameters.
*
* If the desired param does not exist, null will be returned
*
* @example value = $.getURLParam("paramName");
*/ 
	getURLParam: function(strParamName) {
		var strReturn = "";
		var strHref = window.location.href;
		var bFound=false;

		var cmpstring = strParamName + "=";
		var cmplen = cmpstring.length;

		if ( strHref.indexOf("?") > -1 ) {
			var strQueryString = strHref.substr(strHref.indexOf("?")+1);
			var aQueryString = strQueryString.split("&");
			for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
				if (aQueryString[iParam].substr(0,cmplen)==cmpstring) {
					var aParam = aQueryString[iParam].split("=");
					strReturn = aParam[1];
					bFound=true;
					break;
				}
			}
		}
		if (bFound==false) return null;
		return strReturn;
	}
});

function URLDecode(encodedString) {
	if (!encodedString) {
		return '';
	};
	var output = encodedString;
	var binVal, thisString;
	var myregexp = /(%[^%]{2})/;
	while ((match = myregexp.exec(output)) != null && match.length > 1 && match[1] != '') {
		binVal = parseInt(match[1].substr(1),16);
		thisString = String.fromCharCode(binVal);
		output = output.replace(match[1], thisString);
	}
	return output;
}

function copyToInvoicebox() {
	$("#storecontactform [name='invoice_title']").val($("#storecontactform [name='name']").val());
	//$("#basketform [name='invoice_address']").val($("#basketform [name='address']").val());
}

function setBasketItemQt(sku, qt) {
	$.post("/store/basket/set/", {sku:sku, qt:qt, sid:sid}, function(result) {
		window.location.reload();
	}, "json");
}

function reloadBasketList() {
	$("#basket-list").load("/store/basket/list/" + sid + '?time=' + (new Date()).getTime());
}

function addToWishList(id, price) {
	if (parseInt(id, 10) > 0) {
		$.post("/store/wishlist/add", {id:id, price:price}, function(data) {
			$("#addtowishlist").fadeOut();
		}, "json");
	}
}

function removeWishlist(id) {
	if (parseInt(id, 10) > 0) {
		$.post('/store/wishlist/remove', {id:id}, function(data) {
			$("#wishlist-row-"+id).fadeOut();
		}, 'json');
	};
}


