function GetXmlHttpObject()
{
  var xmlHttp=null;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
  return xmlHttp;
}


function updateSideCart(){

	var xmlHttp = GetXmlHttpObject();
	
    var params = "";
    xmlHttp.open("POST", "/browse/cart/action/updateSideCart/", true);

    //Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
	  xmlHttp.onreadystatechange = function() { 
 	    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var response = new String(xmlHttp.responseText);
			document.getElementById('sideCart').innerHTML = response;
		  
        }
	}
	xmlHttp.send(params);
}

function updateProducQuantytInCart(idop, idproduct){

	var xmlHttp = GetXmlHttpObject();
	quanty = document.getElementById('opQuanty_' + idproduct).value;
    var params = "idop=" + idop + "&quanty=" + quanty;
    xmlHttp.open("POST", "/browse/cart/action/updateProductQuanty/", true);

    //Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
	  xmlHttp.onreadystatechange = function() { 
 	    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var response = new String(xmlHttp.responseText);
			document.getElementById(idproduct).innerHTML = response;
		  
        }
	}
	xmlHttp.send(params);
}

function addToCart(idproduct, idprice){

	var xmlHttp = GetXmlHttpObject();
    var params = "idproduct=" + idproduct + "&idprice=" + idprice;
    xmlHttp.open("POST", "/browse/cart/action/add/", true);

    //Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
	  xmlHttp.onreadystatechange = function() { 
 	    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var response = new String(xmlHttp.responseText);
			document.getElementById(idproduct).innerHTML = response;
		  
        }
	}
	xmlHttp.send(params);
}

function jUpdate(idproduct, idprice, price, money, cntid, size, color){

	var xmlHttp = GetXmlHttpObject();
    var params = "idproduct=" + idproduct + "&idprice=" + idprice + "&size=" + size + "&color=" + color + "&split=1";
    xmlHttp.open("POST", "/browse/cart/action/add/", true);

    //Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
	  xmlHttp.onreadystatechange = function() { 
 	    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var response = new String(xmlHttp.responseText);
			document.getElementById(idproduct).innerHTML = response;		  
			var containertxt = response.split("|");

			var cnt = document.getElementById(cntid).value;
			var idop = containertxt[0];
			var idorder = containertxt[1];
			var inner = document.getElementById(idproduct);
	
			if(cnt > 1){
		
				changeProductCount(idop, idorder, cnt);
		
				for(i=1; i<=cnt; i++){
					updateSidebarCart('1', price, money);
				}
		
			} else {
				updateSidebarCart('1', price, money);   
			}
	
			inner.innerHTML = '<a href="/browse/cart/action/basket/" style="color: #b75d05;  text-decoration: none;" onMouseOver=\'this.style.color = \"#de740d\"; document.addcart.src=\"/htdocs/images/default/shopping_cart_hover.png\" \' onMouseOut=\'this.style.color = \"#b75d05\"; document.addcart.src=\"/htdocs/images/default/shopping_cart.png\" \'><img name="addcart" src="/htdocs/images/default/shopping_cart.png" style="border: none; float: right;">&nbsp;&nbsp;<div style="clear:both;"></div><div style="float: right; font-size:13px; ">Маркирани стоки до момента</div></a>';			
        }
	}
	xmlHttp.send(params);
}

function addToCart1(idproduct, idprice, divname, cart_lang, size, color){

    var xmlHttp = GetXmlHttpObject();
    var params = "idproduct=" + idproduct + "&idprice=" + idprice + "&size=" + size + "&color=" + color;
    xmlHttp.open("POST", "/browse/cart/action/add/", true);

    //Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
	  xmlHttp.onreadystatechange = function() { 
 	    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var response = new String(xmlHttp.responseText);
			//document.getElementById(divname+"_"+idproduct).innerHTML = "<a href='/browse/cart'>"+cart_lang+"</a>";
		  
        }
	}
	xmlHttp.send(params);
}

function changeProductCount(idop, idorder, count){ 

	var xmlHttp = GetXmlHttpObject();
    var params = "idop=" + idop + "&idorder=" + idorder +"&count=" + count;
    xmlHttp.open("POST", "/browse/cart/action/count/", true);

    //Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
	  xmlHttp.onreadystatechange = function() { 
 	    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var response = new String(xmlHttp.responseText);
			document.getElementById("all_price").innerHTML = response;
        }
	}
	xmlHttp.send(params);
}

function changeMark(mark){ 

	var xmlHttp = GetXmlHttpObject();
    var params = "mark=" + mark;
    xmlHttp.open("POST", "/browse/mark/name/"+mark, true);

    //Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
	  xmlHttp.onreadystatechange = function() { 
 	    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var response = new String(xmlHttp.responseText);
			document.getElementById("mark").innerHTML = response;
        }
	}
	xmlHttp.send(params);
}


function updateSidebarCart(addtotal, addprice, money_format){

	var total = document.getElementById('cart_total_input').value;
	var price = document.getElementById('cart_sum_input').value;
	var total_inner = document.getElementById('cart_total');
	var price_inner = document.getElementById('cart_sum');
	var newtotal;
	var newprice;
	
	newtotal = Number(total)+Number(addtotal);
	newprice = Number(price)+Number(addprice);
	newprice = Math.round(newprice*100) / 100;
	
	total_inner.innerHTML = '<input type="hidden" id="cart_total_input" name="cart_total_input" value="'+newtotal+'"><strong>'+newtotal+'</strong>';
	price_inner.innerHTML = '<input type="hidden" id="cart_sum_input" name="cart_sum_input" value="'+newprice.toFixed(2)+'"><strong>'+newprice.toFixed(2)+' '+money_format+'</strong>';
	
}

function updateSidebarCartDecr(addtotal, addprice, money_format, type, celem){

	var curnum = document.getElementById(celem).value;
	if (curnum != 1 || type == 'del') {
		var total = document.getElementById('cart_total_input').value;
		var price = document.getElementById('cart_sum_input').value;
		var total_inner = document.getElementById('cart_total');
		var price_inner = document.getElementById('cart_sum');
		var newtotal;
		var newprice;
		
		newtotal = Number(total)-Number(addtotal);
		newprice = Number(price)-Number(addprice);
		newprice = Math.round(newprice*100) / 100;
		
		if (type == 'del') {
			if(newtotal < 0){
				newtotal = 0;
				newprice = 0;
			}
		} else {
			if(newtotal < 1){
				newtotal = 1;
				newprice = price;
				newprice = Math.round(newprice*100) / 100;
			}
		}
		
		total_inner.innerHTML = '<input type="hidden" id="cart_total_input" name="cart_total_input" value="'+newtotal+'"><strong>'+newtotal+'</strong>';
		price_inner.innerHTML = '<input type="hidden" id="cart_sum_input" name="cart_sum_input" value="'+newprice.toFixed(2)+'"><strong>'+newprice.toFixed(2)+' '+money_format+'</strong>';
	}
}

function emp(id){
	var val = document.getElementById(id).value;
	var bval = document.getElementById('b'+id).value;
	
	document.getElementById('b'+id).value = val;
	document.getElementById(id).value = '';
}

function re(id){
	
	var val = document.getElementById(id).value;
	var bval = document.getElementById('b'+id).value;
	
	if(val == '' || val == '0')
		document.getElementById(id).value = bval;
}

function incr2(id, item, tot){
	var pcnt = document.getElementById(id);
	var pcntval = document.getElementById(id).value;
	var calc = 0;
	
	pcnt.value = (Number(pcntval)+1);

	calc = pcnt.value * document.getElementById(item).innerHTML;
	document.getElementById(tot).innerHTML = calc.toFixed(2);
}

function decr2(id, item, tot){
	var pcnt = document.getElementById(id);
	var pcntval = document.getElementById(id).value;
	var calc = 0;
	
	pcnt.value = (Number(pcntval)-1);
	if(pcnt.value < 1){
		pcnt.value = 1;
	}

	calc = pcnt.value * document.getElementById(item).innerHTML;
	document.getElementById(tot).innerHTML = calc.toFixed(2);
}

function deleteFromCart(idop, idorder){ 
	var xmlHttp = GetXmlHttpObject();
	var params = "idop=" + idop + "&idorder=" + idorder;
	xmlHttp.open("POST", "/browse/cart/action/delete/", true);
	//Send the proper header information along with the request
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var response = new String(xmlHttp.responseText);
			//document.getElementById(idop).innerHTML = "";
			if(response == 0) {
				//document.getElementById("whole_cart").innerHTML = "<div class=\"boxProductContent\" align=\"center\" style=\"padding-top: 10px;\"><b>��������� � ������</b><br><br></div><br></td></tr>";
				//document.getElementById("asd").innerHTML = "";
			}
			document.getElementById("all_price").innerHTML = response;
		}
	}
	xmlHttp.send(params);
}

function removeRow(id) {
	var tr = document.getElementById(id);
	if (tr) {
		if (tr.nodeName == 'TR') {
			var tbl = tr; // Look up the hierarchy for TABLE
			while (tbl != document && tbl.nodeName != 'TABLE') {
				tbl = tbl.parentNode;
			}

			if (tbl && tbl.nodeName == 'TABLE') {
				while (tr.hasChildNodes()) {
					tr.removeChild( tr.lastChild );
				}
				tr.parentNode.removeChild( tr );
			}
		} else {
			alert( 'Specified document element is not a TR. id=' + id );
		}
	} else {
		alert( 'Specified document element is not found. id=' + id );
	}
}

function editUserInfo() {
	var name = document.getElementById('name').innerHTML;
	var city = document.getElementById('city').innerHTML;
	var zip = document.getElementById('zip').innerHTML;
	var address = document.getElementById('address').innerHTML;
	var	phone = document.getElementById('phone').innerHTML;
	var	email = document.getElementById('email').innerHTML;
	
	document.getElementById('name').innerHTML = "<input type='text' name='name' id='name2' class='edit_input' value='" + name.replace(/(<([^>]+)>)/ig,"") + "' /><span id='error_name'></span>";
	document.getElementById('city').innerHTML = "<input type='text' name='city' id='city2' class='edit_input' value='" + city.replace(/(<([^>]+)>)/ig,"") + "' /><span id='error_city'></span>";
	document.getElementById('zip').innerHTML = "<input type='text' name='zip' id='zip2' class='edit_input' value='" + zip.replace(/(<([^>]+)>)/ig,"") + "' /><span id='error_zip'></span>";
	document.getElementById('address').innerHTML = "<input type='text' name='address' id='address2' class='edit_input' value='" + address.replace(/(<([^>]+)>)/ig,"") + "' /><span id='error_address'></span>";
	document.getElementById('phone').innerHTML = "<input type='text' name='phone' id='phone2' class='edit_input' value='" + phone.replace(/(<([^>]+)>)/ig,"") + "' /><span id='error_phone'></span>";
	document.getElementById('email').innerHTML = "<input type='text' name='email' id='email2' class='edit_input' value='" + email.replace(/(<([^>]+)>)/ig,"") + "' /><span id='error_email'></span>";
	document.getElementById('edit_button').innerHTML = "<a href='javascript:;' class='edit_data' onClick='saveUserInfo();'>ЗАПАЗВАНЕ НА ИНФОРМАЦИЯТА</a>";
}


function saveUserInfo() {
	var name = document.getElementById('name2').value;
	var city = document.getElementById('city2').value;
	var zip = document.getElementById('zip2').value;
	var address = document.getElementById('address2').value;
	var	phone = document.getElementById('phone2').value;
	var	email = document.getElementById('email2').value;
	
	var xmlHttp = GetXmlHttpObject();
	var params = "name=" + name + "&city=" + city + "&zip=" + zip + "&address=" + address + "&phone=" + phone + "&email=" + email; 
	xmlHttp.open("POST", "/index/profile/", true);
	//Send the proper header information along with the request
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var response = new String(xmlHttp.responseText);
			if(response == "undefined|undefined|undefined|undefined|undefined|undefined") {
				document.getElementById('name').innerHTML = "<strong>" + name + "</strong>";
				document.getElementById('city').innerHTML = "<strong>" + city + "</strong>";
				document.getElementById('zip').innerHTML = "<strong>" + zip + "</strong>";
				document.getElementById('address').innerHTML = "<strong>" + address + "</strong>";
				document.getElementById('phone').innerHTML = "<strong>" + phone + "</strong>";
				document.getElementById('email').innerHTML = "<strong>" + email + "</strong>";
				document.getElementById('edit_button').innerHTML = "<a href='javascript:;' class='edit_data' onClick='editUserInfo();'>РЕДАКТИРАНЕ НА ИНФОРМАЦИЯТА</a>";
			} else {
				//alert(response);
				var containertxt = response.split("|");
				if (containertxt[4] != "undefined")
					document.getElementById("error_name").innerHTML = containertxt[4];
				if (containertxt[2] != "undefined")
					document.getElementById("error_city").innerHTML = containertxt[2];
				if (containertxt[5] != "undefined")
					document.getElementById("error_zip").innerHTML = containertxt[5];
				if (containertxt[3] != "undefined")
					document.getElementById("error_address").innerHTML = containertxt[3];
				if (containertxt[1] != "undefined")
					document.getElementById("error_phone").innerHTML = containertxt[1];
				if (containertxt[0] != "undefined")
					document.getElementById("error_email").innerHTML = containertxt[0];
			}
		}
	}
	xmlHttp.send(params);
}


// Функця за ъпдейтване на данните за адрес
function updateInfo(field, value, error_name){

    //ако не е попълнено полето
    if(value==''){
         document.getElementById('error_'+field).innerHTML=' Моля въведете '+error_name;
    }else{
        document.getElementById('error_'+field).innerHTML='';
    }

     
        var xmlHttp = GetXmlHttpObject();

    var params = "field="+ field +"&value="+ value;
    xmlHttp.open("POST", "/index/updateInfo/", true);

    //Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {




        }
    }

    xmlHttp.send(params);
 

 

}


function subscribe() {
	var	email = document.getElementById('email').value;
	var xmlHttp = GetXmlHttpObject();
	var params = "&email=" + email; 
	xmlHttp.open("POST", "/index/subscribe/", true);
	//Send the proper header information along with the request
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			document.getElementById('email').style['color'] = "#ff0000";
			document.getElementById('email').value = "Вие се записахте успешно!";
		}
	}
	xmlHttp.send(params);
}

function cust_confirm(message, callback) {
	$('#confirm').modal({
		closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
		position: ["20%",],
		overlayId: 'confirm-overlay',
		containerId: 'confirm-container', 
		onShow: function (dialog) {
			var modal = this;

			$('.message', dialog.data[0]).append(message);

			// if the user clicks "yes"
			$('.yes', dialog.data[0]).click(function () {
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				// close the dialog
				modal.close(); // or $.modal.close();
			});
		}
	});
}


function openPopupWait(message,callback){
    $('#waiting').modal({
		closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
		position: ["20%",],
		overlayId: 'confirm-overlay',
		containerId: 'confirm-container',
		onShow: function (dialog) {
			var modal = this;	
                        $('.message', dialog.data[0]).append(message);

                        
                        // if the user clicks "yes"
			$('.yes', dialog.data[0]).click(function () {
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				// close the dialog
				modal.close(); // or $.modal.close();
			});
		}
	});

}



function addEmailWaiting(email, idproduct){




    var xmlHttp = GetXmlHttpObject();

    var params = "idproduct="+ idproduct +"&email="+ email;
    xmlHttp.open("POST", "/browse/addEmailWaiting/", true);

    //Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {


    }
    }

    xmlHttp.send(params);
}


 function checkInsertEmail(){

                            if(document.getElementById('input_email').value == ""){
                                alert("Моля попълнете полето 'Въведете E-mail'");
                            }
                            else {

                                var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                                var address = document.getElementById('input_email').value;
                                if(reg.test(address) == false) {
                                    alert('Моля попълнете валиден  Email');
                                    return false;
                                }else{
                                    addEmailWaiting( document.getElementById('input_email').value, document.getElementById('wait').value );  closeLightBox( 'popupwaiting' );
                                }


                            }
                        }



function openPopupuslovia(){
	// Load dialog on page load
	//$('#basic-modal-content').modal();

	// Load dialog on click
	
	$('#confirm').modal({
		closeHTML: "<a href='#' title='Close' class='modal-close1'>x</a>",
		position: ["20%",],
		overlayId: '',
		containerId: 'confirm-container1',
		onShow: function () {
			var modal = this;
                        
		
			// if the user clicks "x"
			$('.modal-close1').click(function () {
				
				modal.close(); //  $.modal.close();
			});

                       
		}
	});
	
}





function autohide(message, miliseconds) {
	$('#autohide').modal({
		closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
		position: ["20%",],
		overlayId: 'confirm-overlay',
		containerId: 'confirm-container', 
		onShow: function (dialog) {
			var modal = this;

			$('.message', dialog.data[0]).append(message);

			setTimeout("$.modal.close()", miliseconds); // or $.modal.close();
		}
	});
}


function submitOrder() {

                var p1 = document.getElementById('p1').checked;
                var p2 = document.getElementById('p2').checked;
                var p3 = document.getElementById('p3').checked;

    		var txt = document.getElementById('comment').innerHTML;
    		if (txt == 'Коментари относно поръчката можете да въведете в това поле...') {
    			document.getElementById('comment').innerHTML = '';
    		}

                if(document.getElementById('name2').value==''){
                    alert("Не сте въвели данни за 'Лице за контакти'");
                    return false;

                }else if(document.getElementById('city2').value==''){
                     alert("Не сте въвели данни за 'Град'");
                    return false;

                }else if(document.getElementById('address2').value==''){
                     alert("Не сте въвели данни за 'Адрес'");
                    return false;
                }else if(document.getElementById('phone2').value==''){
                     alert("Не сте въвели данни за 'Телефон'");
                    return false;
                }else if (p1 != true && p2 != true && p3 != true) {
                        alert('Моля изберете начин за плащане!');
                }else{
                   document.orderform.submit();
                }

    	}
