BROWSER = new Object();
BROWSER.isOpera = navigator.userAgent.indexOf("Opera") > -1;
BROWSER.isIE    = navigator.userAgent.indexOf("MSIE") > 1 && !BROWSER.isOpera; 
BROWSER.isMoz   = navigator.userAgent.indexOf("Mozilla/5.") == 0 && !BROWSER.isOpera;

compareSelectedValues = [];

if (typeof($) != "function") $ = function(ID) { return document.getElementById(ID); }

function clearValue(textfieldId, imgID) {
	var item = document.getElementById(textfieldId);
    if (imgID) {
		img = $(imgID);
		if (img.tagName == "IMG") {
			img.height = 0;
		}
		if (img.tagName == "DIV") {
		    img.innerHTML = "";
		}
	}
	item.value = "";
}

editorWin = null;
function openHTMLEditor(contentID, previewID, editText) {
   var loc = 'htmledit.php?field=' + contentID;
   var previewObj = document.getElementById(previewID);
   if (previewObj) loc += "&preview=" + previewID;
   if (editText) loc += "&edittext=1";
   var d = new Date()
   var ID = d.getDate()+""+d.getMonth()+1+""+d.getFullYear()+""+d.getHours()+""+d.getMinutes()+""+d.getSeconds();
   editorWin = window.open(loc, '_new'+ID, 'width=880, height=550, scrollbars=no, resizable=yes');
   editorWin.focus();
}

function redirect(id) {
   alert("This link works only in front-end site!")
}

function popupimg(img) {
    var d = new Date()
    var ID = d.getDate()+""+d.getMonth()+1+""+d.getFullYear()+""+d.getHours()+""+d.getMinutes()+""+d.getSeconds();

	var loc = "/enlarge.php?src=" + img;
	var win = window.open(loc, "_new"+ID,"toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=200,height=200");
	win.location.href = loc;
	win.focus();
}

// Display image/flash when input field source was changed
function setImage(imgInput, img) {
	var inputObj = document.getElementById(imgInput);
	if (!imgInput) return false;
	var imgObj = document.getElementById(img);
	if (!imgObj) return false;
	inputObj.imgObj = imgObj; 
	
	inputObj.onchange = inputObj.onblur = function() {
    	
    	if (this.value == this.currentValue) return;
    	
    	var ishowObj = document.getElementById('ishow_'+this.imgObj.id);
    	var isIMG = this.value.match(/\.(jpg|gif|png|bmp)$/ig), val;
    	
        if (this.value.match(/.(swf|flv)$/)) {
		    var divNode = document.createElement('DIV');
		    divNode.id = this.imgObj.id;
		    val = this.value.match(/.swf$/) ? this.value : "/flash/mediaplayer.swf?file=" + this.value + "&title=" + this.value;
		    this.imgObj.parentNode.replaceChild(divNode, this.imgObj);
		    this.imgObj = document.getElementById(divNode.id);
		    if (ishowObj) ishowObj.style.height = "230px";
		    var so = new SWFObject(val, "mymovie", "240", "230", "8");
	        so.addVariable("width","240");
      	    so.addVariable("height","230");
		    so.write(divNode.id);
		} else if (this.imgObj.tagName == "DIV" && isIMG){
		    var imgNode = document.createElement('IMG');
		    imgNode.id = this.imgObj.id;
		    imgNode.border = "0";
			this.imgObj.parentNode.replaceChild(imgNode, this.imgObj);
			this.imgObj = document.getElementById(imgNode.id);
			var Img = new Image();
			Img.src = this.value;
			ishowObj.style.height = "0px";
			this.imgObj.height = 0;
			this.imgObj.src = this.value;
			Img.virtualImg = this.imgObj;
			Img.onload = function(){ this.virtualImg.height = this.height; }
			this.imgObj.onerror = function() { this.height = 0; }
			this.imgObj.virtualImg = Img;
			this.imgObj.ishowObj = ishowObj;
			var res = executeSlow("setImageHeight('"+ this.imgObj.id +"')", 2);
			if (BROWSER.isMoz || BROWSER.isOpera) ishowObj.style.height = "auto";
			if (BROWSER.isOpera && !res) this.imgObj.height = 0;
		} else if (this.imgObj.tagName != "DIV" && isIMG) {
			var Img = new Image();
			Img.src = this.value;
			this.imgObj.height = 0;
			this.imgObj.src = this.value;
			Img.virtualImg = this.imgObj;
			Img.onload = function(){ this.virtualImg.height = this.height; }
			this.imgObj.onerror = function() { this.height = 0; }
			this.imgObj.virtualImg = Img;
			this.imgObj.ishowObj = ishowObj;
			var res = executeSlow("setImageHeight('"+ this.imgObj.id +"')", 2);
			if (BROWSER.isMoz || BROWSER.isOpera) ishowObj.style.height = "auto";
			if (BROWSER.isOpera && !res) this.imgObj.height = 0;
		} else if (this.imgObj.tagName == "DIV" && !isIMG) {
			if (this.value.match(/^\s*$/)) {
				this.imgObj.innerHTML =  '';
				if (ishowObj) ishowObj.style.height = "0px"; 
			} else { 
			    this.imgObj.innerHTML = '<div style="cursor:pointer" onclick="VALIDATE.redirect(\'/download.php?file='+ this.value +'\', true)">Download</div>';
			    if (ishowObj) ishowObj.style.height = "20px";
			}
			
		} else {
			//this.imgObj.height = 0;
		    var divNode = document.createElement('DIV');
		    divNode.id = this.imgObj.id;
		    this.imgObj.parentNode.replaceChild(divNode, this.imgObj);
		    this.imgObj = document.getElementById(divNode.id);
			if (this.value.match(/^\s*$/)) {
			    this.imgObj.innerHTML = '';
			    if (ishowObj) ishowObj.style.height = "0px";
			} else {
			 	this.imgObj.innerHTML = '<div style="cursor:pointer" onclick="VALIDATE.redirect(\'/download.php?file='+ this.value +'\', true)">Download</div>';
			    if (ishowObj) ishowObj.style.height = "20px";
			}
		}
		this.currentValue = this.value;
	}
}

function setImageHeight(imgID) {
   var Img = document.getElementById(imgID);
   if (!Img) return false;
   if (Img.virtualImg.fileSize>0 || (BROWSER.isOpera && Img.virtualImg.height>0)) {
      if (Img.ishowObj) Img.ishowObj.style.height = (parseInt(Img.height) > 250 ? "250px" : parseInt(Img.height)+"px");
      Img.height = Img.virtualImg.height;
      if (BROWSER.isMoz || BROWSER.isOpera) Img.ishowObj.style.height = "auto";
      return true;
   } else {
      return false;
   } 
} 

function executeSlow(func, seconds, counter) {
   if (!counter) counter = 0;
   var res = eval(func);
   if (res) return true;
   else if (counter>=seconds*1000) return false;
   else setTimeout("executeSlow(\""+func+"\","+seconds+","+(counter+100)+")", 100);
}

MANAGER = new Object();

// open file manager window
MANAGER.openFileManager = function(fieldID) {
   var loc = "../backoffice/ajaxfilemanager/ajaxfilemanager.php";
   openWin(loc, 'fileManager', 820, 420, "");
   MANAGER.field = document.getElementById(fieldID);
}

// handle file manager returned url
MANAGER.handleURL = function(url) {
	if (!MANAGER.field) return;
	MANAGER.field.value = url;
	if (typeof(MANAGER.field.onchange) == "function") MANAGER.field.onchange();
} 

// open classic popup window
var win_array = [];
function openWin(loc, winName, winWidth, winHeight, winParams){
   if (!win_array[winName]) win_array[winName] = null;
   if (!win_array[winName] || (win_array[winName] && win_array[winName].closed)){
      if (winParams=='full'){
         winParams = 'resizable=yes,menubar=yes,status=yes,toolbar=yes,titlebar=yes,location=yes,directories=yes,scrollbars=yes';
      }
      win_array[winName] = window.open(loc, winName, "width="+winWidth+",height="+winHeight+","+winParams);
   }

   win_array[winName].location = loc;
   win_array[winName].focus();
   return win_array[winName];
}


// open modal dialog window
function openModal(loc, param, dWidth, dHeight, winParams){
   if (winParams=='full'){
      winParams = 'resizable:yes,status:yes;scroll:yes;help:yes;edge:raised;unadorned:yes';
   }
   if (typeof(winParams)=='undefined'){
      winParams = 'resizable:yes,status:no;scroll:yes;help:yes;edge:raised;unadorned:yes';
   }
      
   if (window.showModalDialog){
       window.showModalDialog(loc, param, "dialogWidth:"+dWidth+"px;dialogHeight:"+dHeight+"px;"+winParams);
   }
   else {
       var win = window.open(loc, 'editWin','height='+dHeight+',width='+dWidth+',toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes');
	   win.location = loc;
       win.focus();
   }
}

function in_array(el, arr) {
	for(var i=0; i<arr.length; i++) if (arr[i] == el) return true;
	for(var i in arr) if (arr[i] == el) return true;
	return false;
}

// Change color of elements with lightTagName,
// which are children of elemID. It works on mouse over/out event.
function hoverLight(elemID, lightTagName, ignoreTags) {
	var elem = $(elemID);
	if (!elem) return;
	var elems = elem.getElementsByTagName(lightTagName);
	for(var i=0; i<elems.length; i++) {
		elems[i].oldColor = elems[i].style.backgroundColor;
		elems[i].onmouseover = function(){
			var children = this.getElementsByTagName('*');
			for(var i=0; i<children.length; i++) {
			    if (this.ignoreTags && this.in_array(children[i].tagName, this.ignoreTags)) continue;
				children[i].style.backgroundColor = "#DCE4F5";
		    }
		}
		elems[i].onmouseout = function() {
			var children = this.getElementsByTagName('*');
			for(var i=0; i<children.length; i++) {
				if (this.ignoreTags && this.in_array(children[i].tagName, this.ignoreTags)) continue;
				children[i].style.backgroundColor = this.oldColor;
		    }
		}
		if (ignoreTags) elems[i].ignoreTags = ignoreTags.split(",");
		// hack for Mozilla
		elems[i].in_array = in_array;
	}
}

// Check All
function check(formName, fieldName, allName) {
    var theform = document.forms[formName];
    var checks = theform[fieldName];
    if (!checks.length){
        checks.checked = theform[allName].checked;
    }
    for (i = 0; i < checks.length; i++) {
         checks[i].checked = theform[allName].checked;
    }
}

// Check one
function validateChecks(formName, fieldName, allName){
    var theform = document.forms[formName];
    var checks = theform[fieldName];
    var fullchecked = true;
    if (!checks.length){
        fullchecked = checks.checked ? true : false
    }
    for (i = 0; i < checks.length; i++) {
         if (!checks[i].checked){ 
             fullchecked = false;
             break;
         }
    }
    if (theform[allName].checked && !fullchecked) theform[allName].checked = false;
    if (!theform[allName].checked && fullchecked) theform[allName].checked = true;
}

function initCheckboxHandler(formName, fieldName, allName) {
    var theform = document.forms[formName];
    var checks = theform[fieldName];
    if (!checks.length) {
    	checks.onclick = new Function("validateChecks('" + formName + "','" + fieldName + "','" + allName + "')");
    } 
    for (i = 0; i < checks.length; i++) {
    	checks[i].onclick = new Function("validateChecks('" + formName + "','" + fieldName + "','" + allName + "')");
    }
    theform[allName].onclick = new Function("check('" + formName + "','" + fieldName + "','" + allName + "')");
    validateChecks(formName, fieldName, allName);
}

function syncPreview(srcID, targetID) {
   var src = document.getElementById(srcID);
   var target = document.getElementById(targetID);
   if (!src || !target) return false;
   src.target = target;
   src.onkeyup = function(){ this.target.innerHTML = this.value; }
}

function setBannerSizeInfo(selectID, infoID) {
	var sel = document.getElementById(selectID);
	var info = document.getElementById(infoID);
	if (!sel || !info) return;
	if (!sel.infoBlock){
	    sel.infoBlock = {"sel":sel, "info":info};
	    sel.onchange = sel.onkeyup = function(){ 
	    	var val = this.options[this.selectedIndex].getAttribute("info");
	    	this.infoBlock.info.innerHTML = val ? val : ""; 
	    }
	    sel.onchange();
	}
}

function setInternalURL(srcID, targetID, init) {
	var src = document.getElementById(srcID);
	var target = document.getElementById(targetID);
	if (!target || !src) return;
	if (!init && src.value == "---") {
		target.value = "";
	} else if (!init) {
		target.value = src.value;
	}
	if (!target.optionsArr){
		target.optionsArr = [];
		target.srcSelect = src;
		for(var i=0; i<src.options.length; i++){
			target.optionsArr[i] = src.options[i].value;
		}
	}
	target.onkeyup = function(){
		if (!this.optionsArr) return;
		for(var i=0; i<this.optionsArr.length; i++){
			if (this.optionsArr[i] == this.value){
				this.srcSelect.selectedIndex = i;
				return;
			}
		}
		this.srcSelect.selectedIndex = 0;
	}
}


EXPAND_REDIRECT = new Object();
EXPAND_REDIRECT.go = function () {
	var i, j, tmp = null;
    var redirectContent = document.getElementById('rcontainer');
	var cond = (document.getElementById('redirected').checked ? 'hidden' : 'visible');
	
	with(EXPAND_REDIRECT) {
	if (!stripContent || stripLength<=0) {
	    alert("Wait loading of page please");
		return false;
	}

	redirectContent.style.visibility = (cond == "hidden" ? 'visible' : 'hidden');
	for (i=0; i<stripContent.length; i++) {
	     if (i<stripIndex) {
			 tmp = document.getElementById(stripContent[i]);
	 		 if (tmp) {
	 		 	 tmp.style.visibility = cond;
	 		 	 if (cond == "hidden" && (tmp.type=="text" || tmp.type == "textarea")) tmp.value = "";
	 		 }
	 		 tmp = document.getElementById("l"+stripContent[i]);
	 		 if (tmp) tmp.style.visibility = cond;
	     } else {
		     for(j=0; j<=stripLength; j++) {
				 tmp = document.getElementById(stripContent[i]+j);
		 		 if (tmp) {
		 		 	tmp.style.visibility = cond;
		 		 	if (cond == "hidden" && (tmp.type=="text" || tmp.type == "textarea")) tmp.value = "";
		 		 }
		 		 tmp = document.getElementById("l"+stripContent[i]+j);
		 		 if (tmp) tmp.style.visibility = cond;
		     }
	     }
	}
	}
}

function stripText(text)  {
  text = text.toLowerCase();

  // strip all non word chars
  text = text.replace(/\W/g, ' ');

  // replace all white space sections with a dash
  text = text.replace(/\ +/g, '-');

  // replace dashes with a dash
  text = text.replace(/\-+/g, '-');

  // trim dashes
  text = text.replace(/^\-+/, '');
  text = text.replace(/\-+$/, '');

  return text;
}


// Villy 
// disable and enable checkbox
function disableCheckbox(id, manid)
{
	elem = document.getElementById(id);
	manelem = document.getElementById(manid);
	if(manelem.checked==true)
	{
		elem.disabled = true;
	}
	else
	{
		elem.disabled = false;
	}
	
}
// Only numbers and point
function noAlpha(obj){
	reg = /[^0-9.]/g;
	obj.value =  obj.value.replace(reg,"");
 }

function isChecked(id)
{
	elem = document.getElementById(id);
	if(elem.checked == true)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
// disable and enable multiple checkbox
function disableMultipleCheckbox(id,nameEl)
{
	var elem  = document.getElementById(id);
	var group = document.form1.elements;
	if(elem.checked == true)
	{
		for(var i = 0, n = group.length; i < n; ++i) 
		{
			//alert(group[i].name);
			if('checkbox' == group[i].type && group[i].name == nameEl ) 
			{
				group[i].disabled=true;
			}
		}
	}
	else
	{
		for(var i = 0, n = group.length; i < n; ++i) 
		{
			//alert(group[i].name);
			if('checkbox' == group[i].type && group[i].name == nameEl ) 
			{
				group[i].disabled=false;
			}
		}
	}
}
function getXMLHTTP() { //fuction to return the xml http object
		var xmlhttp=false;	
		try{
			xmlhttp=new XMLHttpRequest();
		}
		catch(e)	{		
			try{			
				xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e){
				try{
				req = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch(e1){
					xmlhttp=false;
				}
			}
		}
		 	
		return xmlhttp;
	}
	
	
	
	function createCheckBox(strURL, valueEl) 
	{		
		
		var req = getXMLHTTP();
		
		if (req) {
			
			req.onreadystatechange = function() {
				if (req.readyState == 4) 
				{
					// only if "OK"
					if (req.status == 200) {						
						document.getElementById('category'+valueEl).innerHTML=req.responseText;						
					} else {
						alert("There was a problem while using XMLHTTP:\n" + req.statusText);
					}
				}				
			}			
			req.open("GET", strURL, true);
			req.send(null);
		}
				
	}
	
	
	function checkQtty(strURL, key, oldVal) 
	{		
		
		var req = getXMLHTTP();
		
		if (req) {
			
			req.onreadystatechange = function() {
				if (req.readyState == 4) 
				{
					// only if "OK"
					if (req.status == 200) {				
						//document.getElementById('test').innerHTML=req.responseText;	
						if(req.responseText != 'del' && req.responseText != 'add'){		
							alert(req.responseText);
							document.getElementById('qtty'+key).value=oldVal;			
							//window.location.reload(true);
						}						
					} else {
						alert("There was a problem while using XMLHTTP:\n" + req.statusText);
					}
				}				
			}			
			req.open("GET", strURL, true);
			req.send(null);
		}
				
	}
	
	function checkAvailable(strURL, homePath) 
	{		
		
		var req = getXMLHTTP();
		
		if (req) {
			
			req.onreadystatechange = function() {
				if (req.readyState == 4) 
				{
					// only if "OK"
					if (req.status == 200) {					
						if(req.responseText != 'add'){		
							alert(req.responseText);
							var urlParams = strURL; //cart_check_available.html?qtty=1&add=228
							var addInd = urlParams.lastIndexOf("add=");							
							var productId = urlParams.substring(eval(addInd+4),strURL.length);	
							//alert(productId);	
							window.location=homePath+'product_not_onstock.html?productId=' + productId;
						}
						else {
							window.location=homePath+'cart.html';
						}
					} else {
						alert("There was a problem while using XMLHTTP:\n" + req.statusText);
					}
				}				
			}			
			req.open("GET", strURL, true);
			req.send(null);
		}
				
	}
	
	function formSubmit(id)	{
		document.getElementById(id).submit();
	}
	
	function swapImage(bigId, source)
	{
		elem = document.getElementById(bigId);
		elem.src = source;
	}
	function popupv(fileURL, $title) {

	window.open(fileURL, $title, "toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=505,height=379");
	
	//window.open(fileURL)
  }
  
  function rateProduct(ratingCharacteristicId, ratingValue, searchRating) {
    if(searchRating == true) {
      activeStarBg = "url('/images/ratingSliderStar.gif') -21px 0px no-repeat";
      inactiveStarBg = "url('/images/ratingSliderStar.gif') 0px 0px no-repeat";
    } else {
      activeStarBg = "url('/images/reviewRatingStarActive.gif') no-repeat top left";
      inactiveStarBg = "url('/images/reviewRatingStar.gif') no-repeat top left";
    }
  
    var ratingCharacteristicInput = "rating_characteristic_" + ratingCharacteristicId;
    document.getElementById(ratingCharacteristicInput).value = ratingValue;
    $('#searchSlider').slider('option', 'value', ratingValue);
    
    for(i = 1; i <= 5; i++) {
      starId = ratingCharacteristicId + "RatingStarLink" + i;
      if(i <= ratingValue) {
        document.getElementById(starId).style.background = activeStarBg;
      } else {
        document.getElementById(starId).style.background = inactiveStarBg;
      }
    }
  }
function removeByElement(arrayName,arrayElement) {
    for(var i=0; i<arrayName.length;i++ )
     { 
        if(arrayName[i]==arrayElement)
            arrayName.splice(i,1); 
      } 
}

$(document).ready(function(){
  var selectedManufacturers = [];
  var selectedPriceRange = [];
  var searchCharacteristics = [];
  
  $(".searchByManufacturerCheck").bind("click", function(e){
      if(this.checked == true) {
        selectedManufacturers.push(this.value);      
      } else {
        removeByElement(selectedManufacturers, this.value);
      }
      
    var searchRatingValue = document.getElementById('rating_characteristic_searchByRating').value;
    // ajax post
    var cat_id = document.getElementById('cat_id').value;    
    var dataString = 'searchByManufacturer='+selectedManufacturers+'&searchByManufacturerCategory='+cat_id+'&searchByPrice='+selectedPriceRange+'&searchByRating='+searchRatingValue;
		$.ajax({
      type: "POST",
      url: "category.html",
      data: dataString,
      success: function(data) {
        document.getElementById('searchNumProducts').innerHTML = data;
      }
     });    
   });
   
   $(".searchByPriceCheck").bind("click", function(e){
    if(this.checked == true) {
      selectedPriceRange.push(this.value);      
    } else {
      removeByElement(selectedPriceRange, this.value);
    }
    
    var searchRatingValue = document.getElementById('rating_characteristic_searchByRating').value;
    // ajax post
    var cat_id = document.getElementById('cat_id').value;    
    var dataString = 'searchByManufacturer='+selectedManufacturers+'&searchByManufacturerCategory='+cat_id+'&searchByPrice='+selectedPriceRange+'&searchByRating='+searchRatingValue;
		$.ajax({
      type: "POST",
      url: "category.html",
      data: dataString,
      success: function(data) {
        document.getElementById('searchNumProducts').innerHTML = data;
      }
     }); 
   });   

   $(".SearchByRating").bind("click", function(e){
      
    var searchRatingValue = document.getElementById('rating_characteristic_searchByRating').value;
    // ajax post
    var cat_id = document.getElementById('cat_id').value;    
    var dataString = 'searchByManufacturer='+selectedManufacturers+'&searchByManufacturerCategory='+cat_id+'&searchByPrice='+selectedPriceRange+'&searchByRating='+searchRatingValue;
		$.ajax({
      type: "POST",
      url: "category.html",
      data: dataString,
      success: function(data) {
        document.getElementById('searchNumProducts').innerHTML = data;
      }
    });         
   });
   $("#searchSlider").bind("click", function(e){
   
    var searchRatingValue = document.getElementById('rating_characteristic_searchByRating').value;
    // ajax post
    var cat_id = document.getElementById('cat_id').value;    
    var dataString = 'searchByManufacturer='+selectedManufacturers+'&searchByManufacturerCategory='+cat_id+'&searchByPrice='+selectedPriceRange+'&searchByRating='+searchRatingValue;
		$.ajax({
      type: "POST",
      url: "category.html",
      data: dataString,
      success: function(data) {
        document.getElementById('searchNumProducts').innerHTML = data;
      }
    });         
   });   
   
$(".extendedSearchValues").bind("change", function(e){

  var searchRatingValue = document.getElementById('rating_characteristic_searchByRating').value;
  // ajax post
  var cat_id = document.getElementById('cat_id').value;    

  var characteristicId = this.id;
  characteristicId = characteristicId.match(/\d+/);
  searchCharacteristics[characteristicId] = this.value;
  
  var dataString = 'searchCharacteristics='+searchCharacteristics;
  
		$.ajax({
      type: "POST",
      url: "category.html",
      data: dataString,
      success: function(data) {
        alert(data);
      }
    }); 
  
});   
   
   $("#searchSlider").slider();   
   $('#searchSlider').slider('option', 'min', 0);
   $('#searchSlider').slider('option', 'max', 5);
   $('#searchSlider').slider('option', 'step', 1);
   
   $('#searchSlider').bind('slidechange', function(event, ui) {
    var value = $('#searchSlider').slider('option', 'value');
    rateProduct('searchByRating', value, true);
   });
   
    
   if(document.getElementById('loginErrorWrap')) {
    setTimeout("$('#loginErrorWrap').fadeOut('normal');", 3000);
   }

   $("form :checkbox").change(function () {
      if(this.checked == true) {
        dataString = "addProductCompare=1&productId="+this.id;
      } else {
        dataString = "removeProductCompare=1&productId="+this.id;
      }      
      $.ajax({
        type: "POST",
        url: "category.html",
        data: dataString,
        success: function(data) {
          if(data == " [#select_up_to_3_products#]") {
            alert("You can select up to 3 products");
          }
        }
      });   
    });   
   
});
function requestReviewForm() {
  if(document.getElementById('requestReviewFormWrap').style.display == "none") {
    document.getElementById('requestReviewFormWrap').style.display = "block";
  } else {
    document.getElementById('requestReviewFormWrap').style.display = "none";
  }
}

function requestReview() {

  var requestReviewProduct = document.getElementById('requestReviewProduct').value;
  var requestReviewComment = document.getElementById('requestReviewComment').value;
  var productName = document.getElementById('requestProductName').value;
  var productId = document.getElementById('requestProductId').value;
  
  if (requestReviewComment == "") {
    document.getElementById('requestReviewStatus').innerHTML = "Please write a comment";
  } else {
    var dataString = "requestReview=1&requestReviewProduct="+requestReviewProduct+"&requestReviewComment="+requestReviewComment+"&productName="+productName+"&productId="+productId;   
    $.ajax({
        type: "POST",
        url: "product.html",
        data: dataString,
        success: function(data) {
          document.getElementById('requestReviewStatus').innerHTML = data;
          setTimeout("$('#requestReviewFormWrap').fadeOut('normal');", 2000);
          document.getElementById('requestReviewComment').value = "";
          setTimeout("document.getElementById('requestReviewStatus').innerHTML = 'Your request:';", 2000);
        }
      });   
  }    
}

function commentReview(reviewID, productID) {
  var commentTextArea = 'reviewComment' + reviewID;
  var commentText = document.getElementById(commentTextArea).value;
  var productName = document.getElementById('commentProductName').value;
  var dataString = 'reviewCommentForm=1&reviewComment=' + commentText + '&reviewID=' + reviewID+"&productID="+productID+"&productName="+productName;
  statusObj = document.getElementById('insertCommentStatus'+reviewID);
  $.ajax({
      type: "POST",
      data: dataString,
      url: "product.html",
      success: function(data) {
        if(data != ' [#empty_comment#]') {
        document.getElementById('allReviewComments').innerHTML = data;
        statusObj.innerHTML = "Saved";
        setTimeout("statusObj.innerHTML='Your Comment';", 2000);
        } else {
          statusObj.innerHTML = "Please write a comment!";
        }
      }
    });     
}

        
        function changeRelatedCategory(productId, relatedProductId, relatedCategory) {
          var dataString = "updateCategory=true&product="+productId+"&relatedProduct=" + relatedProductId + "&category=" + relatedCategory;
          $.ajax({
              type: "POST",
              data: dataString,
              url: "productrelatedinsert.php",
              success: function(data) {
                relatedDiv = document.getElementById('relatedProductId_'+relatedProductId);
                relatedDiv.style.background = "#f4ffa1";
                setTimeout('relatedDiv.style.background = "#fff"', 1000);
              }
         });   
          
        }
        
        function deleteRelatedProduct(deleteRelatedProductUrl, id) {
          if (confirm('Do you really want to delete this item?')) {
            jQuery.get(deleteRelatedProductUrl);
            
            divToHide = '#relatedProductId_'+id;
            $(divToHide).css("background","#E6E6E6");
            $(divToHide).hide("slow");      
            for(i =0; i < allRelatedProducts.length; i++) {
              if(allRelatedProducts[i] == "'"+id+"'") {
                allRelatedProducts.splice(i,1);
              }
            }
          }
        }

function showDetails(hide) {
  if(hide != true) {
    document.getElementById('characteristicsMore').style.display = "block";
    document.getElementById('compareShowDetails').style.display = "none";
    document.getElementById('compareHideDetails').style.display = "inline";
  } else {
    document.getElementById('characteristicsMore').style.display = "none";
    document.getElementById('compareShowDetails').style.display = "inline";
    document.getElementById('compareHideDetails').style.display = "none";
  }
}        

function showPopupDescription(close, id) {
  if(close == true) {
    $('.popupDscr').fadeOut("normal");      
  } else {
    var categoryIcon = $('#categoryIcon_'+id);
    var position = categoryIcon.position();
    var left = position.left;
    left = left + 69;
    
    document.getElementById('categoryPopupDescription_'+id).style.display = 'block';
    document.getElementById('categoryPopupDescription_'+id).style.left =  left+'px';
    document.getElementById('categoryPopupDescription_'+id).style.top = position.top+'px';
  }
}

function showDescription(close, id) {
  if(close == true) {
    $('.popupDscr').fadeOut("normal");      
  } else {
    var ratingChar = $('#ratingChar_'+id);
    var position = ratingChar.position();
    var left = position.left;
    left = left;    
    document.getElementById('ratingCharDescription_'+id).style.display = 'block';
    document.getElementById('ratingCharDescription_'+id).style.left =  left+'px';
    document.getElementById('ratingCharDescription_'+id).style.top = position.top+ 15 +'px';
  }
}

$(function() {
  $("#submitPoll").click(function() {

		var voteAnswer = $("input[@name='voteAnswer']:checked").val();
		var currentPoll = $("input#currentPoll").val();
		
		if(voteAnswer == undefined) {
			return false;
		}
		
		var dataString = 'voteAnswer=' + voteAnswer + "&currentPoll=" + currentPoll;
 
		$.ajax({
      type: "POST",
      url: "poll.html",
      data: dataString,
      success: function(data) {
        $('#pollForm').html("<div id='pollResults'></div>");
        $('#pollResults').html(data)
        .hide()
        .fadeIn(500);
      }
     });
    return false;
	});
});
runOnLoad(function(){
  $("input#name").select().focus();
});

function moreFields() {
  var numExistingFields = document.getElementById('numExistingFields').value;
  numExistingFields++;
  var newFields = document.getElementById('externalReviewItemWrap').cloneNode(true);
  newFields.id = '';
  newFields.style.display = 'block';
  var newField = newFields.childNodes;
  for (var i=0;i<newField.length;i++) {
    var theName = newField[i].name
    if (theName)
      newField[i].name = theName + numExistingFields;
    }
  var insertHere = document.getElementById('insertFormElement');
  insertHere.parentNode.insertBefore(newFields,insertHere);
  document.getElementById('numExistingFields').value = numExistingFields;
}

function changeSearch(location) {
  if(location == 2) {
    document.getElementById('googleSearchLocation').value = "012144267575837948271:sm0rsvltfgo";
  } else if(location == 1) {
    document.getElementById('googleSearchLocation').value = "012144267575837948271:zsu2umrii4g";
  }
}

function showAdvancedSearch() {
  if(document.getElementById("advancedSearchFields").style.display == "none") {
    document.getElementById("advancedSearchFields").style.display = "block";
    document.getElementById("showAdvancedSearchLink").innerHTML = "Hide advanced search";
    document.getElementById("advancedSearchVisible").value = "1";
  } else {
    document.getElementById("advancedSearchFields").style.display = "none";
    document.getElementById("showAdvancedSearchLink").innerHTML = "Show advanced search";
    document.getElementById("advancedSearchVisible").value = "0";
  }
}
function findPosX(obj) {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }
  
function findPosY(obj) {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop - 190;
  }
  
function showBalloon(id_div, id_link, show) {
	div_elem = document.getElementById(id_div);
	link_elem = document.getElementById(id_link);
	if(show == 1)
	{	
		div_elem.style.display = 'block';
		x = findPosX(link_elem);
		y = findPosY(link_elem);
		div_elem.style.top = y;
		div_elem.style.left = x;
	}
	else
	{
		div_elem.style.display = 'none';		
	}
}

function clearSearchValues() {
  for (i=0;i<document.basicSearch.elements.length;i++) {
      
      if(document.basicSearch.elements[i].type == 'checkbox') {
        document.basicSearch.elements[i].checked = false;
      } else if(document.basicSearch.elements[i].type == 'select-one') {
        document.basicSearch.elements[i].selectedIndex = 0;
      } else if(document.basicSearch.elements[i].type == 'text') {
        document.basicSearch.elements[i].value = "";
      }
  } 
}

function clearGSearch(action) {
  if(action == "focus") {
    if(document.getElementById('google_search').value == "Google search") {
      document.getElementById('google_search').value = "";
    } 
  } else if(action == "blur") {
    if(document.getElementById('google_search').value == "") {
     document.getElementById('google_search').value = "Google search";
    }
  }
}

function showTypes(id) {
  var frame = document.getElementById("categoryTypeWrap_"+id);
  if(frame.style.display == "none") {
    frame.style.display = "block";
  } else if(frame.style.display == "block") {
    frame.style.display = "none";
  }
}

function manageComments(Action) {
  document.getElementById('ManageCommentsAction').value = Action;
  document.getElementById('reviewCommentsForm').submit(); 
}


function onSubmitReview() {
  var emptyFields = false;
  for (i=0;i<document.reviewProduct.elements.length;i++) {      
    if((document.reviewProduct.elements[i].type == 'hidden' && document.reviewProduct.elements[i].value == "") || (document.reviewProduct.elements[i].type == 'hidden' && document.reviewProduct.elements[i].value == "0")) {
      emptyFields = true;
    } else if (document.reviewProduct.elements[i].type == 'textarea' && document.reviewProduct.elements[i].value == "") {
      emptyFields = true;
    }
  }

  if(emptyFields == true) {
    alert('Please fill in all fields');
  } else {
    formSubmit('reviewProduct');
  }
}