$(function(){
	$('.menu_bg_padd ul li:first').removeClass('menu_item').addClass('first');
	//imageLoader(); 
	if( $('.lightbox').length > 0 ){
		$(".lightbox").lightbox();
	}
})
var znav = true;
$(function(){
	if( $('.cloud-zoom').size() > 0 ){	   
		$('.cloud-zoom').CloudZoom();	
	}
	getHiddenZoom();	   
})
function getHiddenZoom(){
	$('.clickthumb a').click(function(){
		if( znav == false ){
			return false;
		} else {
			znav = false;	
		}
		if( $(this).parents('.thumb').find('.insideimg img').size() == 0 ){ return false; }
		navigation_click = $(this);
		area = $(this).parents('.thumb');
		//alert( area.html() )
		imgHide = $(this).parents('.thumb').find('.insideimg img.z-hide');
		imgShow = $(this).parents('.thumb').find('.insideimg img.z-show');
		command = $(this).attr('class');

		
		if( command == 'z-more' ){
			var totalHide;
			totalHide = imgHide.size();
			if( totalHide > 0 ){
				area.addClass('zoombgcolor');
				//if( area.find('.z-hiddenimg').size() == 0 ){
					navigation_click.parent().append('<a href="#" class="z-hiddenimg"><< images</a>');
				//}
				getHiddenZoom();
				//eq(0).
				imgHide.fadeIn('slow', function(){
					$(this).removeClass('z-hide').addClass('z-show');
					className = $(this).parent().attr('class');
					$('.'+className).CloudZoom();	
					znav = true;
				});
			} else{
				znav = true;
				return false;
			}
		} else if( command == "z-hiddenimg" ){
			var totalShow = imgShow.size();
			//if( totalShow == 1 ){
				area.find('.z-hiddenimg').remove();
			//}
			if( totalShow > 0 ){
				area.removeClass('zoombgcolor');
				//eq( totalShow - 1 ).
				$(imgShow).fadeOut('slow', function(){
					$(this).parent().hide();
					$(this).removeClass('z-show').addClass('z-hide');
					znav = true;
				});
			} else{
				znav = true;
				return false;	
			}
		}
		return false;								
	})	
}

$(function() {
	$('#s5').cycle({
		fx:     'fade',
		speed:  1000,
		timeout: 0,
		pager:  '#nav > ul',
		pagerAnchorBuilder:function(i, el){
			return '<li><a href="#" class="galnav"><img src="/assets/snippets/phpthumb/phpThumb.php?zc=1&w=84&h=60&far=0&src='+$(el).attr('src')+'" /></a></li>';
		}
	});
	$('#fade_image').cycle({ 
		fx:     'fade', 
		speed:  1000, 
		next:   '#s2', 
		timeout: 2500 
	});
	$('#s4').cycle({
		fx:     'fade',
		speed:  1000,
		timeout: 5000,
		pager:  '#pager > ul',
		pagerAnchorBuilder:function(i, el){
			return '<li><a href="#" class="navmenu">'+$(el).attr('title')+'</a></li>';
		},
		before:function(){
			$('.moreevent a img').fadeOut('slow');
			//$('.moreevent').hide();
			$('.moreevent a').attr('href', '/product-list.html?col=' + $(this).attr('name'));
		},
		after:function(){
			$('.moreevent a img').fadeIn('fast');
		}
	});
})


function imageLoader(){
	image = $('img');
	imagenav = new Array;
	
	image.each(function(e){
		imagenav[e] = $(this);
		imagenav[e].hide();
		img = new Image;
		$(img)
		.load(function(){
			imagenav[e].fadeIn(1000);
		})
		.attr('src', imagenav[e].attr('src'))
	})
}
function LoginFirst(formId, type, basketId){
	if(getCookie('islogin') == 1){
		validateProd(formId);
		//$('#'+formId).submit();
	}
	else{
		$('body').append('<div class="layer_back"></div><div id="loginFirst"><p>Before proccess shopping you have to login first.</p><form id="loginForm"><table>'+
				'<tr><td>Email</td><td>:</td><td><input type="text" name="username"  /></td></tr>'+
				'<tr><td>Password</td><td>:</td><td><input type="password" name="password"  /><input type="hidden" name="service" value="login" /></td></tr>'+
				'<tr><td></td><td></td><td><input type="button" class="but" onclick="goLogin(\''+formId+'\', \''+type+'\', \''+basketId+'\');" value="Login"  /><input type="button" value="Register" onclick="javascript:location=\'/identify.html\'" /><input type="button" onclick="cancelLogin();" value="Cancel" /></td></tr>'+
				'<tr id="login_loading"><img src="/assets/templates/puriselaka/images/loading.gif" border="0" />Loading...</tr></table></form></div>');
		$('.layer_back').css({opacity:0.7, height:getPageSize()[1]})
		LoginwidthTotal = $('#loginFirst').css('width');
		leng = LoginwidthTotal.length-2;
		Loginwidth = LoginwidthTotal.substr(0,leng);
		$("#loginFirst").css({top: topoffset() + 150, left: (screen.width - Loginwidth)/2 }).hide();
		$("#loginFirst").fadeIn(1000);
		$("#container").css({opacity:0.3});
		return false;
	}
}
function validateProd(formId){
	/*totalPrice = Number($('.qty').length);
	var valQty = 0;
	for(x=1; x<=totalPrice; x++){
		if( $('#qty_'+x).val() > 0 ){
			valQty = 1;
		}
	}
	if( valQty == 1 )*/
		$('#'+formId)[0].submit();
	/*else{
		alert( 'at least you fill one of qty value' )	
	}*/
}
function cancelLogin(){
	$('#loginFirst').remove();
	$('.layer_back').remove()
	$("#container").css({opacity:1});
}
function goLogin(formId, type, basketId){
	ajaxdata = $("#loginForm").serialize();
	$('.but').attr('disabled', 'disabled');
	$('#login_loading').fadeIn('fast');
	$.ajax({
		type:"POST",
		url:"/ajaxhandle/",
		dataType:'json',
		data:"act=login&"+ajaxdata,
		success: function(msg){
			if( msg['out'] == "true" ){
				cancelLogin()
				validateProd(formId);
			}
			else{
				$('#login_loading').hide();
				$('.but').removeAttr('disabled');
				alert("Invalid email or password, plese try again..");
			}
		}
	});
}
function passThisFirst(formid, input, type, basketid, callback){
	var NonBlank=/[\S]/;
	var GoodInt=/^\d+$/;
	var GoodSignedInt=/^(\+|-)?\d+$/;
	var GoodChar=/^[\w\-]+$/;
	var GoodEmail=/^\w[\w\-\.]+\@\w[\w\-]+(\.\w[\w\-]+)+$/;
	
	var contactform = $("#"+formid+" :input");
	var serializeform = $("#"+formid).serialize();
	var lengthinput = $("#"+formid+" :input").length;
	var i = 0;
	for (i=0;i<lengthinput;i++)
	{
		
		var idinput = contactform[i];
		var valform = $(idinput).attr("valform");
		//var textFalse = new Array();
		textFalse = $(idinput).attr("valformword");
		
		if(valform == "NonBlank"){
			var validateform = NonBlank;
		}
		else if(valform == "GoodInt"){
			var validateform = GoodInt;
		}
		else if(valform == "GoodEmail"){
			var validateform = GoodEmail;
		}
		
		if( valform != null )
		{
			if( !validateform.test($(idinput).val()) || $(idinput).val() == 0)
			{
				alert(textFalse);
				var outputfalse = 1;
				return false;
			}
		}
	}
	
	if(outputfalse != 1)
	{
		/*if( typeof( callback === 'function' ) ){
			callback(input, type, basketid);
		}*/
		$("#"+formid).submit();
	}
}
function getCookie(Name){ 
	var re=new RegExp(Name+"=[^;]*", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return null
}

function setCookie(name, value, days){
	if (typeof days!="undefined"){ //if set persistent cookie
		var expireDate = new Date()
		expireDate.setDate(expireDate.getDate()+days)
		document.cookie = name+"="+value+"; path=/; expires="+expireDate.toGMTString()
	}
	else //else if this is a session only cookie
		document.cookie = name+"="+value+"; path=/"
}
function topoffset(){
	var standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body;
	var ie=document.all && !window.opera;
	var dom=document.getElementById;
	var scroll_top=(ie)? standardbody.scrollTop : window.pageYOffset;
	return scroll_top;
}
function getPageSize(){
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) { // all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}


	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}

	var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}
function passtopayment(idForm){
	/*var paymentType = "";
	$('#'+idForm+' [name=paymentType]').each(function(){
		if( $(this).attr('checked') )	{
			paymentType = $(this).val();	
		}												
	});
	if( paymentType == 'paypal' ){
		//$('#' + idForm).attr('action', '/assets/snippets/form_buy/paypal.php');
		//return true;
	}	*/
	return true
}
function AddToBasket(idForm, e){
	$(e).attr('disabled', 'disabled');
	area = $('#' + idForm).parents('.thumb-desc-chart');
	start = area.find('.thumb img');
	end = $('.account-login span a');
	$(e).after('<div class="loading_bag"><img src="/assets/templates/puriselaka/images/loading.gif" /> Please wait...</div>');
	//return false;
	ajaxdata = $('#' + idForm).serialize();
	$.ajax({
		type:"POST",
		url:"/ajaxhandle/",
		dataType:'json',
		data:"act=adbasket&typedata=ajax&"+ajaxdata,
		success: function(msg){
			content = 'MY BAG ['+msg.total+']';
			setTimeout(function(){
			$('.loading_bag').remove();
			animate_box(start, end, content);
			$(e).removeAttr('disabled');
			}, 2000);
		}
	});
	return false;
}
function animate_box(start, end, content){
	posision_start = getSourcePosition(start);
	posision_end = getSourcePosition(end);
	
	if( $('.anmime_border').size() == 0 ){
		$('body').append('<div class="anmime_border"></div>');
	} else{
		return false;	
	}
	$('.anmime_border')
		.css({width:posision_start[0], height:posision_start[1], left:posision_start[2], top:posision_start[3]})
		.animate({
				width:posision_end[0],
				height:posision_end[1],
				left:posision_end[2],
				top:posision_end[3]
			}, 1000, 
			function(){
				$(end).html(content);
				box = $(this);
				setTimeout(function(){
					box.fadeOut('slow', function(){
						$(this).remove();							 
					})
				}, 200);
			}
		);
	return false;
}
function getSourcePosition(source){
	source = $(source);
	pos = source.offset();
	_left = pos.left;
	_top = pos.top;
	_width = source.width();
	_height = source.height();
	return 	new Array(_width, _height, _left, _top);
}
function setcookie (name, value, expires, path, domain, secure) {
    return this.setrawcookie(name, encodeURIComponent(value), expires, path, domain, secure);
}
function setrawcookie (name, value, expires, path, domain, secure) {
    if (typeof expires === 'string' && (/^\d+$/).test(expires)) {
        expires = parseInt(expires, 10);
    }

    if (expires instanceof Date) {
        expires = expires.toGMTString();
    } else if (typeof(expires) === 'number') {
        expires = (new Date(expires * 1e3)).toGMTString();
    }

    var r = [name + '=' + value], s = {}, i = '';
    s = {expires: expires, path: path, domain: domain};
    for (i in s) {
        if (s.hasOwnProperty(i)) { // Exclude items on Object.prototype
            s[i] && r.push(i + '=' + s[i]);
        }
    }
    
    return secure && r.push('secure'),
                    this.window.document.cookie = r.join(";"),
                        true;
}
function GocheckCoupon(e){
	cuponcode = $('#discount_coupon').val();
	$(e).attr('disabled', 'disabled').after('<span class="discountload"><img src="/assets/templates/puriselaka/images/loading.gif" class="imgloaddiscount" /> Proccessing...</span>');
	//attr('disabled', 'disabled').
	$.ajax({
		type:"POST",
		url:"/ajaxhandle/",
		dataType:'json',
		data:"act=getdiscount&c="+cuponcode,
		success: function(msg){
			if( msg.out == "true" ){
				$('#discount_area').hide('slow');
				content = '<label>DISCOUNT</label> : <strong>-'+msg.discount+'</strong>' +
						'<label><font color="#FF0000"><strong style="color:#FF0000">Last Price</strong></font></label> : <strong>'+msg.last_price+'</strong>';
				$('#total_confirmation').append(content)
			}
			else{
				$('.discountload').remove();
				$(e).removeAttr('disabled');
				alert(msg.error);
			}
		}
	});
}
function update_basket(){
	$('#button_update_basket').trigger('click');
}

function forgotPassword(e){

	$('#content-forgot').show('slow');	

}
function delete_basket(){
	c = confirm('Are you sure want to empty basket?');
	if( c ){
		$('#service').val('empty_basket');
		$('#formBasket')[0].submit();
	} else{
		return false;	
	}
}
