// 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;
	if (minprice > 0){
		valid = true;
	}
	
	obj = document.getElementById('maxprice');
	var maxprice = obj.value;
	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

function BasketOper( fpn, catid , reachedBasketLimit , operation )
{
	//alert('reached limit' + reachedBasketLimit);
	// first param is fixed product name , second is category id , third operation specified (optional)
	/*var arrayParam = new Array();
	arrayParam = params.split('_');*/
	if (operation == null)
	{
		if( basketListSt.indexOf( ',' + fpn + ',' ) == -1 )
		{
			//alert(reachedBasketLimit + ' ' + phrase);
			var urlFrom = document.location;
			if (reachedBasketLimit == 'true')
			{
				document.write('<a href="#" 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
		{
			document.write('<a href="myshoppydoo.aspx" title="' + viewBasketText + '" class="a2"><img src="http://img.shoppydoo.com/mysd_ck_on.gif" alt="basket" />' + savedBasketText + '</a>');
		}
	}
	else
	{
		if (operation == 'setminprice')
			document.write('<a href="javascript:void(0);" title="' + setMinPriceInBasketText + '" class="a2" onclick="AddToBasket(\'' + fpn + '\' , ' + catid + ' , \'' + operation + '\');return false;">' + setMinPriceInBasketText + '</a>');
		else
			document.write('<a href="javascript:void(0);" title="' + setAvailabilityInBasketText + '" class="a2" onclick="AddToBasket(\'' + fpn + '\' , ' + catid + ' , \'' + operation + '\');return false;">' + setAvailabilityInBasketText + '</a>');
	}
}

function GoToBasket()
{
	var link = 'myshoppydoo.aspx';
	document.location = link;
}

//********************************************************************

//********************************************************************
// 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.visibility = 'hidden';
	}
	/*
	element = document.getElementById('search');
	if (element) {
		element.focus();
	}
	*/
}

// 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 = QueryValues('minprice');
	var maxPrice = QueryValues('maxprice');
	
	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();
	}
}

//generate a random number between 1 and 1000000.
function GetRandomNumber() {
    var rand_no = Math.ceil(1000000 * Math.random());
    return rand_no;
}