var xmlHttp
	if (!xmlHttp) {
	try {
		  xmlHttp = new XMLHttpRequest();
		}
		catch (e) {
		  xmlHttp=false
		}
		}
		function xmlHttp_send_post(URLto, xmlMessage) {
			xmlHttp.open("POST", URLto, false)
			// for ie compatability
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.send(xmlMessage)
			return xmlHttp.responseText;
		} 

$(document).ready(function(){
		//apply light box effect to every picture having class lightbox
		$(".lightbox").lightbox();
		// prepare draggable big basket
		$("#fullBasket").draggable();	
		$("#tciMsgBox").draggable();
		$("#fullBasket").hide();
		//every time when page referesh update the cart.
		updateCart();		
		///show hide cart:srart ////////////////////////////
		$('#mycart').click(function (){
			//$('#fullBasket').toggleClass('hidden');
			location.href=jSitePath+"/shopping-basket.php";
			
		});
		$('#shoppingBasket').click(function (){
			//$('#fullBasket').toggleClass('hidden');
			
			basketDisplay();
			
			$("#fullBasket").animate({right: 220, opacity: 'show'},"slow");
		});
		///show hide cart:end   ////////////////////////////
		$('.addToCartLink').click(function(){
			alert('testing jquery');
		});
		
		$.post( jSitePath+"/shopping-manupulation.php", {"updateCart":"updateCart"}, function(data){			
			$('#cartItems').html(data.itemcount);
		});
		
		$("#searchgo").click(function(){
			document.getElementById("formsearch").submit();
		});
		///show full cart function 
		$('#showMyCart').click(function (){
			alert('show cart');
			$("#fullBasket").visibility = 'visible';
		});

		$('#createaccountID').hide('slow',function (){			
			$("#Shipping").show('slow');
		});
		/*----------------------- related prodcuts -----------------------*/
		$('#relatedImg').click(function(){
			if($("#relatedImg").attr("src").search("minus")!=-1)
			{
				var imgsrc=$("#relatedImg").attr("src").replace("minus","plus");
				$("#relatedImg").attr({ src:imgsrc });
				$("#relatedProdId").hide('slow');
			}
			else
			{
				var imgsrc=$("#relatedImg").attr("src").replace("plus","minus");
				$("#relatedImg").attr({ src:imgsrc });
				$("#relatedProdId").show('slow');
			}
		});
		/*----------------------- related prodcuts -----------------------*/
		initializeSuggestFramework();
});
function getDiscount(productId)
{		
	$.post( jSitePath+"/shopping-manupulation.php", {"changeStatus":"changeStatus", "productId":productId}, function(data){							
		return data;
	});	
}
function getTax(id)
{	
	$.post( jSitePath+"/shopping-manupulation.php", {"task":"getTax", "productId":id}, function(data){	
			alert("Server Data: "+ data);						
	});	
}
function wishlistProceed()
{
	var frm = document.wishlistFrm;
	var prodId=document.getElementById('prod_id').value;
	if(prodId=='')
	{
		alert(document.getElementById('select_msg').value);
		return ;
	}
	var prodid_array=prodId.split(",");
	
	for(i=0;i<prodid_array.length;i++)
	{
		if(prodid_array[i])
		{
			var pId=document.getElementById('pId'+prodid_array[i]).value;
			var pQuantity=document.getElementById('pQuantity'+prodid_array[i]).value;
			var pPrice=document.getElementById('pPrice'+prodid_array[i]).value;
			var pName=document.getElementById('pName'+prodid_array[i]).value;
			var pCustDiscount='';
			var pCatId=document.getElementById('pCatId'+prodid_array[i]).value;
			var pModel=document.getElementById('pModel'+prodid_array[i]).value;
			var pTax=document.getElementById('pTax'+prodid_array[i]).value;

			var pMinQty=document.getElementById('pMinQty'+prodid_array[i]).value;
			var pMaxQty=document.getElementById('pMaxQty'+prodid_array[i]).value;
			var pStockAvailable=document.getElementById('pStockAvailable'+prodid_array[i]).value;
			var pAllowBackorder=document.getElementById('pAllowBackorder'+prodid_array[i]).value;
			var pBackorderQty=document.getElementById('pBackorderQty'+prodid_array[i]).value;
			var pTotalStockQty=document.getElementById('pTotalStockQty'+prodid_array[i]).value;
			var pWeight=document.getElementById('pWeight'+prodid_array[i]).value;
			var pExtraShipCharge=document.getElementById('pExtraShipCharge'+prodid_array[i]).value;
			
			if(pStockAvailable=='0' && pAllowBackorder=='0')
			{
				var backorder=0;
				var extraship=0;
			}
			if(pStockAvailable=='0' && pAllowBackorder=='1')
			{
				var backorder=1;
				var extraship = parseFloat(pExtraShipCharge);
					extraship=extraship.toFixed(2);
			}
			
			var chk = xmlHttp_send_post(jSitePath+"/shopping-manupulation.php","add=add&pId="+pId+"&qty="+pQuantity+"&price="+pPrice+"&name="+pName+"&tax="+pTax+"&weight="+pWeight+"&categoryId="+pCatId+"&itemCode="+pModel+"&extraship="+extraship+"&min_qty="+pMinQty+"&max_qty="+pMaxQty+"&back_qty="+pBackorderQty+"&stock_avaliable="+pStockAvailable+"&backorder="+backorder+"&tot_qty="+pTotalStockQty+"&wishlistOrder=yes");
			
			/*if(chk){
				alert(chk);
				break;
			}else {
				addToCart(pId,pQuantity,pPrice,pName,pTax,pWeight,pCatId, pModel, pCustDiscount,'order_incomplete',pMinQty,pMaxQty,pTotalStockQty,pAllowBackorder,pBackorderQty,pExtraShipCharge,pStockAvailable);
			}*/
		}
	}
	document.location="shopping-basket.php";

}
function validateOrderProceed(prod_count)
{
	var totalProdPrice='0';
	for(i=1;i<=prod_count;i++)
	{
		var pId=document.getElementById('pId'+i).value;
		var pQuantity=document.getElementById('pQuantity'+i).value;
		var pPrice=document.getElementById('pPrice'+i).value;
		var pName=document.getElementById('pName'+i).value;
		var pCustDiscount=document.getElementById('pCustDiscount'+i).value;
		var pCatId=document.getElementById('pCatId'+i).value;
		var pModel=document.getElementById('pModel'+i).value;
		var pFeatureName=document.getElementById('pFeatureName'+i).value;

		var pMinQty=document.getElementById('pMinQty'+i).value;
		var pMaxQty=document.getElementById('pMaxQty'+i).value;
		var pStockAvailable=document.getElementById('pStockAvailable'+i).value;
		var pAllowBackorder=document.getElementById('pAllowBackorder'+i).value;
		var pBackorderQty=document.getElementById('pBackorderQty'+i).value;
		var pTotalStockQty=document.getElementById('pTotalStockQty'+i).value;
		var pWeight=document.getElementById('pWeight'+i).value;
		var pExtraShipCharge=document.getElementById('pExtraShipCharge'+i).value;
		var pBackorder=document.getElementById('pBackorder'+i).value;
		var pTax=document.getElementById('pTax'+i).value;
		//if(pBackorder=='1')
		var chk = xmlHttp_send_post(jSitePath+"/shopping-manupulation.php","add=add&pId="+pId+"&qty="+pQuantity+"&price="+pPrice+"&name="+pName+"&weight="+pWeight+"&categoryId="+pCatId+"&itemCode="+pModel+"&extraship="+pExtraShipCharge+"&min_qty="+pMinQty+"&max_qty="+pMaxQty+"&back_qty="+pBackorderQty+"&stock_avaliable="+pStockAvailable+"&backorder="+pBackorderQty+"&tot_qty="+pTotalStockQty+"&order_backorder="+pBackorder+"&featureName="+pFeatureName+"&org_price="+pPrice+"&tax="+pTax+"&checkOrderProceed=yes");
		//prompt("",chk);
	}	
	document.view_order.submit();
}

function addToCart(id,qty,price,name,tax,weight,catid, code, custDiscount,order_incomplete,min_qty,max_qty,tot_qty,allow_back,back_qty,extraship,stock_avaliable,inc_tax_price,tax_rates)
{	//alert(inc_tax_price+' ' +tax_rates);return false;
	if(inventory=='1')
	{
		if(parseInt(qty) < 1 || qty == ''){
			alert(please_enter_quantity); 
			return false;
		}if(stock_avaliable=='0' && allow_back=='0'){
			var backorder=0;
			var extraship=0;
		}if(stock_avaliable=='0' && allow_back=='1'){
			var backorder=1;
			var extraship = parseFloat(extraship);
				extraship=extraship.toFixed(2);
		}
	}
	var org_tax_rates=(parseFloat(tax_rates)+100);
	var org_tax_rates=(parseFloat(org_tax_rates)/100);
	var org_price=(parseFloat(price)/org_tax_rates).toFixed(2);

	$.post( jSitePath+"/shopping-manupulation.php", {"add":"add", "productId":id, "qty":qty, "price":inc_tax_price, "name":name, "tax":tax, "weight":weight, "categoryId":catid, "itemCode":code,"custDiscount":custDiscount,"backorder":backorder,"extraship":extraship,"min_qty":min_qty,"max_qty":max_qty,"allow_back":allow_back,"back_qty":back_qty,"stock_avaliable":stock_avaliable,"tot_qty":tot_qty, "org_price":org_price, "tax":tax_rates}, function(data){	
		if(data){
			alert(data);
			return false;
		}else {
			$('#shoppingcartbg').fadeOut().fadeIn();		
			updateCart(id,price);
			//if(order_incomplete!='order_incomplete'){*/
				document.getElementById('light').style.display='block';
				document.getElementById('fade').style.display='block';
				document.getElementById('fade').style.height=parseInt(document.body.clientHeight)+'px';
				document.getElementById('light').style.top=parseInt(document.documentElement.scrollTop)+parseInt(200)+'px';
				document.getElementById('product_msg').innerHTML=productAdded+' '+name;
			/*}else to complete order from myaccount section
				document.view_order.submit();	*/
		}
	});
	
	
}
function addToCartDetail(id,qty,price,name,tax,weight,catid, code, featurename,min_qty,max_qty,tot_qty,allow_back,back_qty,extraship,stock_avaliable,inc_tax_price,tax_rates,is_feature)
{
	
	var addProduct='set';
	if(is_feature=='yes'){
		if(featurename==''){
			alert(selectFeature);
			var addProduct='unset';
		}
	}

	if(addProduct=='set')
	{
		var flag = true;
		if(inventory=='1')
		{
			if(allow_back=='0' && stock_avaliable=='0'){
				alert(out_of_order_msg); 
				return false;
			}

			if(parseInt(qty) < 1 || qty == '')
			{
				alert(please_enter_quantity); 
				return false;
			}
			if(stock_avaliable=='0' && allow_back=='0')
			{
				var backorder=0;
				var extraship=0;
			}
			if(stock_avaliable=='0' && allow_back=='1')
			{
				var backorder=1;
				var extraship = parseFloat(extraship);
					extraship=extraship.toFixed(2);
			}
		}

		var org_tax_rates=(parseFloat(tax_rates)+100);
		var org_tax_rates=(parseFloat(org_tax_rates)/100);
		var org_price=(parseFloat(price)/org_tax_rates).toFixed(2);
		
		if(flag)
		{
			$.post( jSitePath+"/shopping-manupulation.php", {"add":"add", "productId":id, "qty":qty, "price":inc_tax_price, "name":name, "tax":tax, "weight":weight, "categoryId":catid, "itemCode":code, "featureName":featurename,"backorder":backorder,"extraship":extraship,"min_qty":min_qty,"max_qty":max_qty,"allow_back":allow_back,"back_qty":back_qty,"stock_avaliable":stock_avaliable,"tot_qty":tot_qty, "org_price":org_price, "tax":tax_rates}, function(data){	
			if(data)
			{
				alert(data);
				return false;
			}
			else {
				
				$('#shoppingcartbg').fadeOut().fadeIn();
				updateCart();
				document.getElementById('light').style.display='block';
				document.getElementById('fade').style.display='block';
				document.getElementById('fade').style.height=parseInt(document.body.clientHeight)+'px';
				document.getElementById('light').style.top=parseInt(document.documentElement.scrollTop)+parseInt(200)+'px';
				document.getElementById('product_msg').innerHTML=productAdded+' '+name;
			}
			});
		}
	}
}
/////////////Testimonials///////////////////////
function showReviewForm()
{
	$("#reviewBox").show();	
}

function submitReview(priductId, review)
{
	if(review=='')
	{
		alert(please_enter_review);
		return false;
	}
	$.post( jSitePath+"/shopping-manupulation.php", {"sendReview":"sendReview", "productId":priductId, "review":review}, function(data){	
		if(data=='sended')
			alert(review_sent_alert);
		$("#reviewBox").hide();	
		$("#writeReview").hide();
		
	});
}
/////////////Testimonials///////////////////////
function updateCart()
{
	$.post( jSitePath+"/shopping-manupulation.php", {"updateCart":"updateCart"}, function(data){		
			var myObject = eval('(' + data + ')');						
			//alert(data);
			discountAlert(myObject['total']);
			if(myObject)
			{				
				total_qnt = parseFloat(myObject['total_qnt']);//changed for total quantity
				price = parseFloat(myObject['total']);
				price = price.toFixed(2);
				$('#cartItems').html(''+myObject['itemcount']+'');
				$('#cartTotal').html(''+price+'');
				$('#totalQnt').html(''+total_qnt+'');//changed for total quantity

			}
	});
	
	basketDisplay();
	
}
function updateCartPrice(id,price)
{
	
	$.post( jSitePath+"/shopping-manupulation.php", {"updateCartPrice":"updateCartPrice", "productId":id,"price":price}, function(data){		
			var myObject = eval('(' + data + ')');						
			//alert(data);
			discountAlert(myObject['total']);
			if(myObject)
			{	
				total_qnt = parseFloat(myObject['total_qnt']);//changed for total quantity
				price = parseFloat(myObject['total']);
				price = price.toFixed(2);
				$('#cartItems').html(''+myObject['itemcount']+'');
				$('#cartTotal').html(''+price+'');
				$('#totalQnt').html(''+total_qnt+'');//changed for total quantity
			}
	});
	
	basketDisplay();
	
}

function discountAlert(total)
{
	if(total >= (defDiscountPrice - 10) && total < defDiscountPrice)
	//alert(discount_alert1);
	alert(lbl_if_purchse + defDiscountPrice + lbl_or_more + defDiscountPercent + lbl_disc_on_total);
}




function basketDisplay()
{
	//alert(jSitePath);
	$.ajax({
		url : jSitePath+"/basket/basket.php",
		success : function (data) {
		$("#fullBasket").html(data);
		}
	});
}


//**********************Drag Drop Function ***************************************//

/**
* Event delgation jQuery Drag & Drop and Resize Plug-in based on EasyDrag 1.4
* Batiste Bieler : http://batiste.dosimple.ch/blog/
*
* Credits: http://fromvega.com
*/

$(function($){

    // to track if the mouse button is pressed
    var isDragMouseDown    = false;
    var isResizeMouseDown    = false;

    // to track the current element being dragged
    var currentElement = null;

    // global position records
    var lastMouseX;
    var lastMouseY;
    var lastElemTop;
    var lastElemLeft;
    var lastElemWidth;
    var lastElemHeight;

    // returns the mouse (cursor) current position
    var getMousePosition = function(e){
        if (e.pageX || e.pageY) {
            var posx = e.pageX;
            var posy = e.pageY;
        }
        else if (e.clientX || e.clientY) {
            var posx = e.clientX
            var posy = e.clientY
        }
        return { 'x': posx, 'y': posy };
    };

    var offset_snap_grip = function(grid, size) {
        var limit = grid / 2;
        if ((size % grid) > limit) {
            return grid-(size % grid);
        } else {
            return -size % grid;
        }
    }

    // updates the position of the current element being dragged
    var updatePosition = function(e, opts) {
        var pos = getMousePosition(e);

        var _left = (pos.x - lastMouseX) + lastElemLeft;
        var _top = (pos.y - lastMouseY) + lastElemTop;
        
        if(_top<0)
            _top=0;
        if(_left<0)
            _left=0;

        if($(currentElement).hasClass('snap-to-grid')) {
            _left = _left + offset_snap_grip(opts.grid, _left)
            _top = _top + offset_snap_grip(opts.grid, _top)
        }

        currentElement.style['top'] = _top + 'px';
        currentElement.style['left'] = _left + 'px';
    };

    var updateSize = function(e, opts) {
        var pos = getMousePosition(e);

        var _width = (pos.x - lastMouseX + lastElemWidth);
        var _height = (pos.y - lastMouseY + lastElemHeight);

        if(_width<50)
            _width=50;
        if(_height<50)
            _height=50;

        if($(currentElement).hasClass('snap-to-grid')){
            _width = _width + offset_snap_grip(opts.grid, _width)
            _height = _height + offset_snap_grip(opts.grid, _height)
        }

        currentElement.style['width'] = _width + 'px';
        currentElement.style['height'] = _height + 'px';
    };

    // set children of an element as draggable and resizable
    $.fn.dragResize = function(opts) {
        
        
        return this.each(function() {

            // when the mouse is moved while the mouse button is pressed
            $(this).mousemove(function(e) {
                if(isDragMouseDown) {
                    updatePosition(e, opts);
                    return false;
                }
                else if(isResizeMouseDown) {
                    updateSize(e, opts);
                    return false;
                }
            });
    
            // when the mouse button is released
            $(this).mouseup(function(e) {
                isDragMouseDown = false;
                isResizeMouseDown = false;
            });

            // when an element receives a mouse press
            $(this).mousedown(function(e) {

                if($(e.target).hasClass('handle')) {

                    var el = $(e.target).parents('.block')[0];

                    isDragMouseDown = true;
                    currentElement = el;

                    // retrieve positioning properties
                    var pos = getMousePosition(e);
                    lastMouseX = pos.x;
                    lastMouseY = pos.y;

                    lastElemLeft = el.offsetLeft;
                    lastElemTop  = el.offsetTop;

                    updatePosition(e, opts);
                }

                if($(e.target).hasClass('resize')) {
                    var el = $(e.target).parents('.block')[0];

                    isResizeMouseDown = true;
                    currentElement = el;

                    var pos = getMousePosition(e);
                    lastMouseX = pos.x;
                    lastMouseY = pos.y;

                    lastElemWidth  = parseInt(el.style['width'], 10);
                    lastElemHeight = parseInt(el.style['height'], 10);

                    updateSize(e, opts);
                }
                return false;
            });
        });
    };
});

//**********************Drag Drop Function ***************************************//

function isNumberKey(evt)
  {
	 var charCode = (evt.which) ? evt.which : event.keyCode
	 if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	 return true;

  }
  function isNumber(evt)
  {
	 var keycode;
	 if (window.event) keycode = window.event.keyCode;
	 else if (evt) keycode = evt.which;
	 if(keycode=="13")
		  return false;
	 else {
	 	 var charCode = (evt.which) ? evt.which : event.keyCode
		if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	 }
	 return true;

  }
  
function tciMsgBox(msg)
{
	var l = (screen.width - parseFloat($('#tciMsgBox').css('width'))) / 2;
	var t = (screen.top + parseFloat($('#tciMsgBox').css('height'))) / 2;
	$('#tciMsgBox').css('left', l);
	$('#tciMsgBox').css('top', t);
	$('#tciMsg').html(msg+l);
	$('#tciMsgBox').fadeIn();
}  
function checkout(sitePath)
{
	location.href=responseText=sitePath + '/shopping-basket.php';
}
function redirectLogin(sitePath)
{
	location.href=sitePath + '/my-account.php';
}
