$(document).ready(function(){
						   
	$('.shopByTitle').siblings().find('ul').hide();
	$('.expandControl').parent().css({'position':'relative'});
	$('.expandControl').css({'position':'absolute', 'right':5+'px'}).text('+');
	$('.shopByTitle').next().find('ul').slideDown().prev().find('span').text('-');

	$('.shopByTitle').siblings().find('p').click(function(){
		$(this).parent().siblings().find('>ul').hide();
		$(this).next().slideToggle('fast');		
		if($(this).find('span.expandControl').text() == '+'){
			$(this).find('span.expandControl').text('-');
			$(this).parent().siblings().find('p').find('span.expandControl').text('+');
		} else {
			$(this).find('span.expandControl').text('+');
		}
	});
	
		
	$('.gotocart').click(function(){
		var returnValue = false;
		/*$('#shoppingCart table tr').each(function(){
			if($(this).find('input[name="my-item-qty"]').val() == 0 ||	$(this).find('input[name="my-item-qty"]').val() == undefined ||	$(this).find('input[name="my-item-qty"]').val() == null){
				//console.log('entered false condition');
				returnValue = 'false';
				//alert('Please input quantity.');
			} else {
				returnValue = 'true'
				window.location = 'products-check.php';
				return;
				
			}
			if(returnValue == 'true') {
				return;	
			}
			
		});
		if(returnValue == 'false') {
			alert('Please input quantity.');
		}*/
		var i = 0;
		$('#shoppingCart table tr').each(function(){
			var myitemqty = trim($(this).find('input[name="my-item-qty"]').val());
			//console.log('asds'+i+1);
			if(myitemqty != '0' && typeof(myitemqty) != 'undefined' && typeof(myitemqty) != 'NaN' && typeof(myitemqty) != 'null' && trim(myitemqty) != ''){
				//console.log(i+1);
				//console.log(trim($(this).find('input[name="my-item-qty"]').val()));
				//console.log(myitemqty);
				//alert('sadsad'+myitemqty+'sads');
				//console.log('type'+$.type(myitemqty));
				returnValue = true;
			} 
		});
		//console.log('returnValue='+returnValue);
		if(returnValue == false) {
			uialertPopUp('Alert','Please input quantity.');
			//uialert('Please input quantity.');
			returnValue = false;
		} else {
			returnValue = false;
			window.location = 'products-check.php';	
		}
	});
	
	$('.backToShop').click(function(){
		location.assign('products-shop.php?d='+getCookie('shoppaged'));							
	});
	
	$('input[name="jcartItemQty[]"], input[name="my-item-qty"]').css({'text-align':'center'});
	
	$('.errMsgContainer ul').css({'border':'#EEE solid 1px', 'padding':'5px'});
	$('.errMsgContainer ul li').css({'padding':'5px','color':'red'});
	
	$('#registeration_email, #registeration_confirmEmail').blur(function(){
		if($.trim($('#registeration_email').val()) != ''){
			if(!validateEmail($.trim($('#registeration_email').val()))){
				if(uialert('Invalid email address')){
					$(this).css({'background-color':'#FF0'});
				}
			}
		}
	});
	
	$('#copy_billing').change(function(){
	   if($('#copy_billing').attr('checked') == 'checked'){
		   //alert('checked');
			$('#purchase_ship_fname').val($.trim($('#purchase_bill_fname').val()));
			$('#purchase_ship_lname').val($.trim($('#purchase_bill_lname').val()));
			$('#purchase_ship_company').val($.trim($('#purchase_bill_company').val()));
			$('#purchase_ship_address').val($.trim($('#purchase_bill_address').val()));
			$('#purchase_ship_address2').val($.trim($('#purchase_bill_address2').val()));
			$('#purchase_ship_city').val($.trim($('#purchase_bill_city').val()));
			$('#purchase_ship_state').prop('selectedIndex', $('#purchase_bill_state').prop('selectedIndex'));
			$('#purchase_ship_postal').val($.trim($('#purchase_bill_postal').val()));
			$('#purchase_ship_phone1').val($.trim($('#purchase_bill_phone1').val()));
			$('#purchase_ship_phone2').val($.trim($('#purchase_bill_phone2').val()));
			$('#purchase_ship_phone3').val($.trim($('#purchase_bill_phone3').val()));
	   } else {
			$('#purchase_ship_fname').val('');
			$('#purchase_ship_lname').val('');
			$('#purchase_ship_company').val('');
			$('#purchase_ship_address').val('');
			$('#purchase_ship_address2').val('');
			$('#purchase_ship_city').val('');
			$('#purchase_ship_state').val('');
			$('#purchase_ship_postal').val('');
			$('#purchase_ship_phone1, #purchase_ship_phone2, #purchase_ship_phone3').val('');
	   }
	});
	
	/*$('#shipSameAsBillChkBoxLbl').dblclick(function(e){
		e.preventDefault();	
	});*/
	
	//numeric validation 
	$('.phoneNumberContainer input').keydown(function(event){
		if ( event.keyCode == 46 || event.keyCode == 8 ) {	//delete and backspace
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (event.keyCode < 48 || event.keyCode > 57 ) {
                event.preventDefault(); 
            }   
			//alert('Input numbers only');
        }									   
	}).mouseover(function(){
		$(this).attr('title', 'Please input numbers only');	
	}).focus(function(){
		$(this).attr('title', 'Please input numbers only');	
	}).keyup(function(event){								//on key up move focus to next field
		if($(this).val().length == 3) {
			$(this).next('input').focus();
		}
	});
	
	if($.trim($('#itemCountDispthead').attr('lang')) != '') {
		$('#totalItemsQtyHeader').text($('#itemCountDispthead').attr('lang'));
	} else {
		$('#totalItemsQtyHeader').text('0');
	}
	//$('#totalValueHeader').text($('#jcart-subtotal').attr('lang'));
	var num = new Number($('#jcart-subtotal').attr('lang'));
	if(num.toFixed(2) != 'NaN') {
		$('#totalValueHeader').text('$'+num.toFixed(2));
	} else {
		$('#totalValueHeader').text('$0.00');
	}
	//alert(queryStringValue('color'));
	$('#c-'+queryStringValue('color')).css('background','#EFF6F9');
	
	//image zoom close - products shop page
	$('#imgZoomClose').live('click', function() {
		$('#popupContent').fadeOut();
		jui.removeCover();
	});
	
	$('#popupContent').live('blur', function() {
		$('#popupContent').fadeOut();
		jui.removeCover();								 
	});
	
	if($('a').attr('href') == 'index.html') {
		$(this).attr('href','index.php');
	}
	
});	//document ready close

//on window resize
$(window).resize(function() {
						  
	//center the zoomed image
	if($('#popupContent').is(":visible")) {
		$('#popupContent').css('left', get_center_position($('#popupContent').width()+'px'));
		$('#popupContent').css('top', get_center_position_vertical($('#popupContent').height()+'px'));
	}						  
});

function navigate(uriRequest, page){
	//alert(uriRequest);
	location.assign(page+'?req=get&'+$.trim(uriRequest));	
}

function navigateToShop(page, designId, prodId){
	
	location.assign(page+'?d='+$.trim(designId)+'&p='+$.trim(prodId));	
}

function validateAddToCart(obj){
	//alert($(obj).find('input[name="my-item-qty"]').val());
	if($(obj).find('input[name="my-item-qty"]').val() == 0 || $(obj).find('input[name="my-item-qty"]').val() == null || $(obj).find('input[name="my-item-qty"]').val() == undefined){
		uialert('Please Input valid quantity');
		return false;
	} else {
		var name = $.trim($(obj).find('input[name="my-item-id"]').val());
		var value = $.trim($(obj).find('input[name="my-item-qty"]').val());
		if(!getCookie( name )){
			Set_Cookie( name, value, 1, '/', '', '' );
		} else {
			var newVal = parseInt(parseInt(getCookie( name ))+parseInt(value));
			Set_Cookie( name, newVal, 1, '/', '', '' );
		}
		return true;	
	}
}

function Set_Cookie( name, value, expires, path, domain, secure ){
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	if ( expires ){
		expires = expires * 1000 * 60 * 60 * 1;	//expires after one hour
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}
		
function getCookie(c_name){
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++) {
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name)	{
			return unescape(y);
		}
	}
}

//set the quantity field with already checked numbers of items from the cookie
function checkDefaultQuantityValues() {
	$('#shoppingCart table tr').each(function(){
		var nameGet = $(this).find('input[name="my-item-id"]').val();	
		if(nameGet != undefined){
			if(getCookie( nameGet )){
				$('#i-'+nameGet).val($.trim(getCookie( nameGet )));
			}
		}
	});
}

function deleteCookie( cookieName ) {
	Set_Cookie( cookieName, '', -1, '/', '', '' );
}

function querySt(ji) {					//check query string key availability
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[0];
		}
	}
}

function queryStringValue(key) {		//pass query string key and this function returns its value
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == key) {
			return ft[1];
		}
	}
}


function updateTotals(){
	$('#subTotal_check').text(($('#jcart-subtotal strong').text()));	
}

//javascript email validation
function validateEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = email;
   if(reg.test(address) == false) {
	  uialert('Invalid Email Address, Please enter a valid email address.');
	  //return false;
   }
   return true;
}

//show messages in ui alert box
function uialert(alertMSG){
	$( "#dialog-alert p").empty().append('<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>'+alertMSG);
	$( "#dialog-alert" ).dialog({
		resizable: false,
		height: 'auto',
		modal: true,
		buttons: {
			"Ok": function() {
				$( this ).dialog( "close" );
				//location.replace(url);
			}
		}
	});
}

function uialertPopUp(title, alert_msg){
	$( "#dialog-alert-popUp p").empty().append('<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>'+alert_msg);
	$( "#dialog-alert-popUp" ).attr('title', title);
	if(alert_msg.length > 100){
		width = 500;	
	} else {
		width = 300;	
	}
	
	$( "#dialog-alert-popUp" ).dialog({
		resizable: false,
		height: 'auto',
		width:width,
		modal: true,
		buttons: {
			"Ok": function() {
				$( this ).dialog( "close" );
				//location.replace(url);
			}
		}
	});
}

//create page cover
jui.cover_rugs = function() {
	var elements = document.body.getElementsByTagName('*');
	var newDiv = document.createElement('div');
	newDiv.style.width = '100%';
	newDiv.style.height = '100%';
	newDiv.style.border = '1px solid #000';
	newDiv.style.position = 'fixed';
	newDiv.style.backgroundColor = '#000';
	newDiv.style.top = '0';
	newDiv.style.left = '0'
	newDiv.style.opacity = '0.7';
	newDiv.style.zIndex = '200';
	newDiv.style.filter = 'alpha(opacity=70)';
	newDiv.setAttribute('id', 'pageCover');
	document.body.insertBefore(newDiv, elements[0]);
}

//open big image in pop up
function ZoomImage(obj) {
	//alert($(obj).height());
	imgHeight = 600;
	imgWidth = 400;
	var appendContent1 = '<a href="javascript:" id="imgZoomClose" class="cancel greyColor">';
	var appendContent2 = '<img src="images/closeXSymbol.jpg" style="border:none"/>';
	var appendContent3 = '</a><img src="'+$(obj).attr('src')+'" height="'+imgHeight+'" width="'+imgWidth+'"/>';
	$('#imageZoom').empty().append(appendContent1+appendContent2+appendContent3);
	$('#imageZoom').css('padding','10px');
	$('#popupContent').css('left', get_center_position(imgWidth+'px'));
	$('#popupContent').css('height', parseInt(imgHeight+20)+'px');
	$('#popupContent').css('top', get_center_position_vertical(imgHeight+'px'));
	$('#popupContent').css('width', parseInt(imgWidth+20)+'px');
	$('#popupContent').fadeIn(500);
	//$('#popupContent').show();
	jui.cover_rugs();
}	

//get the center position vertically
function get_center_position_vertical(size) {
	size = size.replace(/px/g, '');
	if(size == '' || size == null) {
		alert('Please provide a height value of the popup element to get the center position');
		return false;
	}
	var win_size = get_window_size();
	var win_height = win_size['height'];
	var max_val = Math.max(win_height, size);
	var min_val = Math.min(win_height, size);
	var diff = max_val - min_val;
	var final = Math.round(diff/2);
	return final+'px';
}

function trim( val ) {
	return $.trim(val);
}
