// Get the array of values for a given parameter specified in the query string
function QueryValues (paramName) {
    sArgs = location.search.slice(1).split('&');
    values = new Array();
    count = 0;
    for (var i = 0; i < sArgs.length; i++) {
        if (sArgs[i].slice(0, sArgs[i].indexOf('=')) == paramName) {
            values[count] = sArgs[i].slice(sArgs[i].indexOf('=')+1);
	    count++;
        }
    }

    return values;
}

// Retrieves the list of selected products (selected checkbox)
// Returns an array of products id.
function GetProducts2Compare() {
  // Aggiungere i prodotti della pag corrente checkati che prim aon lo erano
  var prod2compare = new Array();
  
  var checked = GetProductCheckboxes(true);
  var unchecked = GetProductCheckboxes(false);
  
  if (self.prevSelectedProdList) {
	prodCounter = 0;
	// Remove all the products that are not checked anymore.
	for (var i=0; i < prevSelectedProdList.length; i++) {
		var notUnchecked = true;
		for (var j=0; j < unchecked.length; j++) {
			if (prevSelectedProdList[i] == unchecked[j].value) {
				notUnchecked = false;
				break;
			}
		}
		
		if (notUnchecked) {
			prod2compare[prodCounter] = prevSelectedProdList[i];
			prodCounter++;
		}
	}
	  
	// Add the checked products that weren't checked before.
	for (var i=0; i < checked.length; i++) {
		var notPrevChecked = true;
		for (var j=0; j < prevSelectedProdList.length; j++) {
			if (prevSelectedProdList[j] == checked[i].value) {
				notPrevChecked = false;
				break;
			}
		}
		
		if (notPrevChecked) {
			prod2compare[prodCounter] = checked[i].value;
			prodCounter++;
		}	
	}
  } else {
	for (var i=0; i < checked.length; i++) {
		prod2compare[i] = checked[i].value;
	}
  }
  
  return prod2compare;
}

// Reset all the products checkbox
function ResetProducts2Compare() {
	prevSelectedProdList = new Array();
	var checked = GetProductCheckboxes(true);
	
	for (var i=0; i < checked.length; i++) {
		checked[i].checked = false;
	}
}

// Redirect the user to the compare products page
// specifying the list of selected products
function CompareProducts() {
	var productIDs = GetProducts2Compare();
	
	if (productIDs.length > 1) {
		if (productIDs.length <= maxNbrCompare) {
			// Set the list of products to compare
			var formControl = document.getElementById("productsID2Compare");
			if (formControl) {
				formControl.value = productIDs.join(',');
			}
			
			var submitForm = document.getElementById("compareForm");
			submitForm.action = "compare_products.aspx";
			submitForm.submit();
		} else {
			// The maximum number of products to compare has been reached.
			alert("Please, select a maximum of " + maxNbrCompare + " products for comparison.");
		}
	} else {
		if (compareErrorMsg) {
			alert(compareErrorMsg);
		} else {
			alert("Please, select at least two products,\n by checking the corresponding box.");
		}
	}
}

// Removes a product from the compare page
function RemoveProductsFromCompare(prod2remove) {
	var productIDtxt = unescape(QueryValues('selectedProductsID')[0]);
	var productIDs = productIDtxt.split(',');
	
	if (productIDs.length > 2) {
		// remove the selected product from the list of current products.
		var prodsText = "";
		for (var i = 0; i < productIDs.length; i++) {
			if (productIDs[i] != prod2remove) {
			  //This product has to be kept.
			  
			  if (prodsText.length > 0) {
				prodsText += ",";
			  }
			  prodsText += productIDs[i];
			}
		}
		prodsText = escape(prodsText);
		
		var categoryNameText = QueryValues('catName');
		var categoryIdText = QueryValues('categoryid');
		var pageText = QueryValues('page');
		var searchText = QueryValues('search');
		var levelText = QueryValues('level');
		
		var newURL = "compare_products.aspx?selectedProductsID=" + prodsText + 
              "&catName=" + categoryNameText +
              "&categoryid=" + categoryIdText +
							"&page=" + pageText +
							"&search=" + searchText +
							"&level=" + levelText;

		document.location = newURL;
	} else {
		alert("Can't remove: need at least two products to compare.");
	}
}

// Redirect the client to the new category page, 
// specifying the selecetd products
function GoToCategoryPage(baseUrl) {
	var productIDs = GetProducts2Compare().join(',');
	
	if (self.prevSelectedProdList && productIDs != prevSelectedProdList.join(',')) {
		// The list of selected products has changed: need to post to the server
		// the updated list
		var inputText = document.getElementById("selectedProductsID");
		if (inputText) {
			inputText.value = productIDs;
		}
		
		var submitForm = document.getElementById("movePageForm");
		submitForm.action = baseUrl;
		submitForm.submit();
	} else {
		// The list of selected product has remained unchanged: just redirect to
		// the given url
		document.location = baseUrl;
	}
}

// Check the boxes in the page corresponding to one of the
// previosly selecetd products.
function CheckSelectedProducts() {
	var prodBoxes = document.getElementsByName("productid");
	
	if (prodBoxes && self.prevSelectedProdList) {
		for (var i=0; i<prodBoxes.length; i++) {
			// Check the checkbox if it was previosly selected.
			for( var j=0; j<prevSelectedProdList.length; j++ ){
				if( prodBoxes[i].value == prevSelectedProdList[j] ){
					prodBoxes[i].checked = true;
				}
			}
		}
	}
}

// Retrieves the array of product checkboxes whose value matches the 
// one indicated.
// Returns an array of checkboxes.
function GetProductCheckboxes(value) {
	var boxes = new Array();
	var prodBoxes = document.getElementsByName("productid");
	
	if (prodBoxes) {
		var count = 0;
		for (var i=0; i<prodBoxes.length; i++) {
			if (prodBoxes[i].checked == value) {
				boxes[count] = prodBoxes[i];
				count++;
			}
		}
	}
	
	return boxes;
}

// Go back to the page to select more products to add to the comparison page
// baseUrl (string): the url to be put in the action attribute of the form
// selectedProductsId (string): the coma seprated products ID. They are the IDs of the 
//                              products currently under comparison.
function CompareMoreProducts(baseUrl, selectedProductsId) {
	var inputText = document.getElementById("selectedProductsID");
	if (inputText) {
		inputText.value = selectedProductsId;
	}
	
	var submitForm = document.getElementById("addMoreForm");
	submitForm.action = baseUrl;
	submitForm.submit();
}

// Reload the same page, adding extra query parameters.
// paramNames (Array): the names of the parameters to add
// paramValues (Array): the values of the parameters to add. 
//                      The size of this array must be the same as paramNames.
function ReloadPage(paramNames, paramValues) {
  // Use the same page.
  var newURL = location.pathname + "?";
  
  // Add all the parameters, that need to be passed unchanged.
  var sArgs = location.search.slice(1).split('&');
  var argName;
  var argValue;
  
  for (var i = 0; i < sArgs.length; i++) { 
    argName = sArgs[i].slice(0, sArgs[i].indexOf('='));
    argValue = sArgs[i].slice(sArgs[i].indexOf('=') + 1);
    
    if (argName.length == 0 || argValue.length == 0) {
      continue;
    }
    
    // Add this parameter only if it's not one of the parameters
    // passed as input to this function
    addThis = true;
    for (var j = 0; j < paramNames.length; j++) {
      if (paramNames[j] == argName) {
        addThis = false;
        break;
      }
    }
    
    if (addThis) {
      newURL += argName + "=" + argValue + "&";
    }
  }
  
  // Add all the parameters passed to this function
  for (var i = 0; i < paramNames.length; i++) {
    if (paramValues.length > i) 
    {
	  if ( paramValues[i] != '')
	  {
		newURL += paramNames[i] + "=" + paramValues[i] + "&";
	  }
    } else {
      break;
    }
  }
    
  newURL = newURL.substring(0, newURL.length - 1);
  //alert(newURL);
  document.location = newURL;
}

function CheckSearchValidity() {
	var valid = false;
	
    var obj = document.getElementById('search');
	var s = obj.value;
	if (s != '' && s.length >= 2){
		valid = true;
	}
	
	obj = document.getElementById('minprice');
	var minprice = obj.value;
	minprice = minprice.replace(',', '.');
	if (minprice > 0){
		valid = true;
	}
	
	obj = document.getElementById('maxprice');
	var maxprice = obj.value;
	maxprice = maxprice.replace(',', '.');
	if (maxprice > 0){
		valid = true;
	}
	
	if (valid) {
		return true;	    
	} else {
	    alert('Insert at least 2 letters in the search box!');
	    return false;
	}
}

//********************************************************************
// functions for basket

//################################################################
//#   This funcion produces output string shown in page
//#	
//#	fpn							Fixed Product Name
//#	catid							Category Id
//#	reachedBasketLimit		True if limit in basket has been reached
//#	operation					operation to do (optional , e.g. save min price)
//#
function BasketOper( fpn, catid , reachedBasketLimit , operation)
{
	//alert('reached limit' + reachedBasketLimit);
	/*var arrayParam = new Array();
	arrayParam = params.split('_');*/
	var IsInBasket = false;
	var FPNBasketList = new Array();
	FPNBasketList = basketListSt.split(',');
	for (var i=0; i<FPNBasketList.length; i++) 
	{
		//alert(FPNBasketList[i]);
		if (fpn == FPNBasketList[i])
		{
			IsInBasket = true;
		}
	}
	if (operation == null)
	{
		if( basketListSt.indexOf( ',' + fpn + ',' ) == -1 )
		{
			//alert(reachedBasketLimit + ' ' + phrase);
			var urlFrom = document.location;
			if (reachedBasketLimit == 'true')
			{
				document.write('<a href="javascript:void(0);" title="' + saveToBasketText + '" onclick="alert( LimitReachedPhrase );return false;" class="a2"><img src="http://img.shoppydoo.com/mysd_ck_off.gif" alt="basket" />' + saveToBasketText + '</a>');
			}
			else
			{
				//alert('link');
				document.write('<a href="javascript:void(0);" title="' + saveToBasketText + '" class="a2" onclick="AddToBasket(\'' + fpn + '\' , ' + catid + ' , null);return false;"><img src="http://img.shoppydoo.com/mysd_ck_off.gif" alt="basket" />' + saveToBasketText + '</a>');
			}
		}
		else
		{
		    if (isLogged == 'true')
		    { 
		        //alert(isLogged + '------' + userName); 
			    //document.write('<a href="my/' + userName +  '/myshoppydoo/#' + fpn.replace(' ' , '_') + '" title="' + viewBasketText + '" class="a2"><img src="http://img.shoppydoo.com/mysd_ck_on.gif" alt="basket" />' + savedBasketText + '</a>');
			   document.write('<a href="my/' + userName +  '/myshoppydoo#' + fpn.replace(' ' , '_') + '" title="' + viewBasketText + '" class="a2"><img src="http://img.shoppydoo.com/mysd_ck_on.gif" alt="basket" />' + savedBasketText + '</a>'); 
			}
			else
			{
			    //alert(isLogged); 
			    document.write('<a href="myshoppydoo.aspx#' + fpn.replace(' ' , '_') + '" title="' + viewBasketText + '" class="a2"><img src="http://img.shoppydoo.com/mysd_ck_on.gif" alt="basket" />' + savedBasketText + '</a>');
			} 
		}
	}
	else
	{
		if (operation == 'setminprice')
		{
			//alert('is in basket=' + IsInBasket);
			if ((!IsInBasket) && (reachedBasketLimit == 'true'))
				document.write('<a href="javascript:void(0);" title="' + setMinPriceInBasketText + '" onclick="alert( CantDoOperPhrase );return false;" class="a2"><img src="http://img.shoppydoo.com/mysd_ck_off.gif" alt="basket" />' + setMinPriceInBasketText + '</a>');
			else
				document.write('<a href="javascript:void(0);" title="' + setMinPriceInBasketText + '" class="a2" onclick="AddToBasket(\'' + fpn + '\' , ' + catid + ' , \'' + operation + '\');return false;">' + setMinPriceInBasketText + '</a>');	
		}
		else
		{
			if ((!IsInBasket) && (reachedBasketLimit == 'true'))
				document.write('<a href="javascript:void(0);" title="' + setAvailabilityInBasketText + '" onclick="alert( CantDoOperPhrase );return false;" class="a2"><img src="http://img.shoppydoo.com/mysd_ck_off.gif" alt="basket" />' + setAvailabilityInBasketText + '</a>');
			else
				document.write('<a href="javascript:void(0);" title="' + setAvailabilityInBasketText + '" class="a2" onclick="AddToBasket(\'' + fpn + '\' , ' + catid + ' , \'' + operation + '\');return false;">' + setAvailabilityInBasketText + '</a>');
		}
	}
}

//********************************************************************

//********************************************************************
// Used in registration form
function SetUsernameControl(object)
{
	if (object.id.indexOf('rdbNewsLetter') != -1)
	{
		//alert(object.id);
		var buttonYes = document.getElementById('_ctl0_cpForm_CtlRegisterForm_rdbNewsLetter_0');
		var usenameValidator = document.getElementById('_ctl0_cpForm_CtlRegisterForm_reqUserName');
		usenameValidator.enabled = (buttonYes.checked) ? false : true;
		//alert(usenameValidator.enabled);
	}
}
//********************************************************************

// Opens the advanced search box
function OpenAdvSearch()
{
	var element = null;
	
	element = document.getElementById('advancedSearch');
	if (element) {
		element.style.display = 'block'; 
	}
	
	element = document.getElementById('linkAdvSearch'); 
	if (element) {
		element.style.display = 'none'; 
	}
	element = document.getElementById('linkSimpleSearch'); 
	if (element) {
		element.style.display = 'inline';
	}
}

function CloseAdvSearch()
{
	var element = null;
	
	element = document.getElementById('advancedSearch');
	if (element) {
		element.style.display = 'none'; 
	}
	
	element = document.getElementById('linkAdvSearch'); 
	if (element) {
		element.style.display = 'inline';
	}
	
	element = document.getElementById('linkSimpleSearch'); 
	if (element) {
		element.style.display = 'none'; 
	}
}
// Checks if the maxPrice and minPrice are among the page parameters.
// If true, populates the min and max price textboxes and shows the advance search box
function CheckPriceFilter() {
	var minPrice = unescape(QueryValues('minprice')).replace(',', '.');
	var maxPrice = unescape(QueryValues('maxprice')).replace(',', '.');
		
	if (minPrice > 0 || maxPrice > 0) {
		// Populate the price textboxes
		
		var element = null;
		
		element = document.getElementById('minprice');
		if (element) {
			element.value = minPrice; 
		}
		
		element = document.getElementById('maxprice');
		if (element) {
			element.value = maxPrice; 
		}
		
		OpenAdvSearch();
	}
}

function clickButton(buttonId, event) {
    event = event || window.event; 
    if (event.keyCode == 13) {
        var obj = document.getElementById(buttonId);
        if (obj) { 
            obj.click();
            return false;
        }
    }
    return true;
}

//********************************************************************
//----------    this function shows/hides order number area when writing -------------------
//----------    merchant reviews from shoppydoo
//
// objId --->                         id of the object containing objects related to order number
// validatorOrderNumberId -->  id of the validator related to order number
function ShowHideOrderNumber(objId , validatorOrderNumberId)
{
    var bOrderNumberVisible = false;
    var bBuyAdvice = false;
    var nRate = 0;
    var e=document.getElementsByTagName("input");
	for(var i=0;i<e.length;i++)
	{
		if (e[i].id.indexOf('rdbBuyAdvice') != - 1)
		{	
		    if (e[i].checked)
		    { 
			    //alert(e[i].value);
			    if (e[i].value == 'false')
			    {
			        bOrderNumberVisible = true;
			    }
			   bBuyAdvice = e[i].value; 
			 } 
		}
		if (e[i].id.indexOf('lstRate') != - 1)
		{
		    if (e[i].checked)
		    { 
		        nRate = e[i].value;
		    } 
		}
	}
	//alert(nRate);
	bOrderNumberVisible = (bBuyAdvice == 'false') || ((bBuyAdvice == 'false') && (nRate == 3) && (nRate >0)) || ((nRate <= 2) && (nRate >0))
	
	orderNumberElement = document.getElementById(validatorOrderNumberId);
	//alert(orderNumberElement);
	if (orderNumberElement != null)
	{
        if (bOrderNumberVisible)
        {
            ValidatorEnable(orderNumberElement,true);
        }
        else
        {
            ValidatorEnable(orderNumberElement,false);
        }
        var x =new getObj(objId);
         x.style.display = (bOrderNumberVisible) ? 'block' : 'none';
   } 
	
//	var t1 = document.getElementById(tr1);
//	var t2 = document.getElementById(tr2);
   
	
   
//    t1.style.visibility = (bOrderNumberVisible) ? 'visible' : 'hidden';
//    t2.style.visibility = (bOrderNumberVisible) ? 'visible' : 'hidden';
   
//    t2.style.display = (bOrderNumberVisible) ? 'block' : 'none';
}
//********************************************************************
//********************************************************************


//********************************************************************
// functions for lists

function AddToList(listType , FixedProductName , ProductName , URL , imageURL)
{
	//alert('fpn:' + FixedProductName + ' , entity name:' + ProductName + ', url to load:' + URL + ', imageURL :' + imageURL);
	switch (listType)
	{
		case 1:
//			alert('Aggiungo a lista nozze');
			document.location = 'tolist.aspx?type=' + listType + '&name=' + FixedProductName + '&entityname=' + ProductName + '&source=' + escape(URL) + '&imageurl=' + imageURL;
		break;
	}
}

//********************************************************************
// Utils functions
function hideimg(img) {
   if(img) {
       //img.height = 0;
       //img.width = 0;
       img.style.display='none';
   }
}
