var SEP = ',';
var productFormName = 'ProductDetailsForm';
var comparePhonesFormName = 'CompareMaterialProductsForm';
var updateCheckoutCookie = true;

///////////////////////////////////////////////////////////////////////////////
// Manufacturer/Model selection event handlers
///////////////////////////////////////////////////////////////////////////////

//Sets up apropriate items in listboxes.
function populateCompareItems(default_model_option, productId1, productId2, productId3, separator)
{
    if (productId1 == "" && productId2 == "" && productId3 == "") {
        return;
    }
    var productIDs = new Array(3);
    productIDs[0]  = productId1;
    productIDs[1]  = productId2;
    productIDs[2]  = productId3;
    for(var i = 0; i < productIDs.length; i++) {
        if ( productIDs[i].length > 0 ) {
            for(var j = 0; j < i; j++) {
               if ( productIDs[j].length == 0 ) {
                   productIDs[j] = productIDs[i];
                   productIDs[i] = "";
                   break;
               }
            }
        }
    }

    for(var productSelIdx = 1; productSelIdx <= 3; productSelIdx++) {
        var curManufSelect = document.getElementById("selectManufacturer" + productSelIdx);
        var curModelSelect = document.getElementById("compareItem" + productSelIdx);
        var productID = productIDs[productSelIdx-1];

        // if no product on current position
        if ( productID.length == 0 ) {
            curModelSelect.options[0].selected = true;
            curManufSelect.options[0].selected = true;
            continue;
        }

        for(var i = 0; i != curManufSelect.options.length; i++) {
            var curOption = curManufSelect.options[i];

            if ( curOption.value.length == 0 )
                continue;

            var items = getDependentItems(curOption.value);
            for (var iItems = 0; iItems < items.length; iItems++) {
                var item = items[iItems];
                var itemId = getIdfromComposition(item.idComboKey,separator);
//                alert('[itemId = ' + itemId + '][phoneID = ' + phoneID + ']');
                if ( itemId == productID ) {
                    curOption.selected = true;
                    eval("selectManufacturerOnChange" + productSelIdx + "('" + default_model_option + "');");
                    curModelSelect.options[iItems+1].selected = true;
                    break;
                }
            }
       }
    }
}

// reads compared products informations from page URL and sets up apropriate items in listboxes.
function populateCompareItemsFromURL(default_model_option, separator)
{
    if (document.location.search == "" || document.location.search == 'undefined' || document.location.search.length <= 1 )
        return;
    var params = document.location.search.substr(1,document.location.search.length);
    var productIDs = new Array(3);
    productIDs[0] = getIdfromComposition(getURLParamValue(params,"compareItem1"), separator);
    productIDs[1] = getIdfromComposition(getURLParamValue(params,"compareItem2"), separator);
    productIDs[2] = getIdfromComposition(getURLParamValue(params,"compareItem3"), separator);

    for(var i = 0; i < productIDs.length; ++i) {
        if ( productIDs[i].length > 0 ) {
            for(var j = 0; j < i; ++j) {
               if ( productIDs[j].length == 0 ) {
                   productIDs[j] = productIDs[i];
                   productIDs[i] = "";
                   break;
               }
            }
        }
    }

    for(var productSelIdx = 1; productSelIdx <= 3; ++productSelIdx) {
        var curManufSelect = document.getElementById("selectManufacturer" + productSelIdx);
        var curModelSelect = document.getElementById("compareItem" + productSelIdx);
        var productID = productIDs[productSelIdx-1];

        // if no product on current position
        if ( productID.length == 0 ) {
            curModelSelect.options[0].selected = true;
            curManufSelect.options[0].selected = true;
            continue;
        }

        for(var i = 0; i != curManufSelect.options.length; ++i) {
            var curOption = curManufSelect.options[i];

            if ( curOption.value.length == 0 )
                continue;

            var items = getDependentItems(curOption.value);
            for (var iItems = 0; iItems < items.length; ++iItems) {
                var item = items[iItems];
                var itemId = getIdfromComposition(item.idComboKey, separator);
                if ( itemId == productID ) {
                    curOption.selected = true;
                    eval("selectManufacturerOnChange" + productSelIdx + "('" + default_model_option + "');");
                    curModelSelect.options[iItems+1].selected = true;
                    break;
                }
            }
       }
    }
}

//This function is used to update the values of the model select box on the products compare page, when a new manufacturer is selected
//
function selectManufacturerOnChange1(default_model_option) {

  document.forms[comparePhonesFormName].compareItem1.options.length= 0;
  document.forms[comparePhonesFormName].compareItem1.options[0]= new Option(default_model_option, "");

  var items = getDependentItems ( document.forms[comparePhonesFormName].selectManufacturer1.value );

  for (var i = 0; i < items.length; ++i) {

    var item = items[i];
    document.forms[comparePhonesFormName].compareItem1.options[i + 1] = new Option(item.name, item.idComboKey + ',' + item.image + ',' + item.description);
  }
}

//This function is used to update the values of the model select box on the products compare page, when a new manufacturer is selected
//
function selectManufacturerOnChange2(default_model_option) {

  document.forms[comparePhonesFormName].compareItem2.options.length= 0;
  document.forms[comparePhonesFormName].compareItem2.options[0]= new Option(default_model_option, "");

  var items = getDependentItems ( document.forms[comparePhonesFormName].selectManufacturer2.value );

  for (var i = 0; i < items.length; ++i) {

    var item = items[i];
    document.forms[comparePhonesFormName].compareItem2.options[i + 1] = new Option(item.name, item.idComboKey + ',' + item.image + ',' + item.description);
  }
}

//This function is used to update the values of the model select box on the products compare page, when a new manufacturer is selected
//
function selectManufacturerOnChange3(default_model_option) {

  document.forms[comparePhonesFormName].compareItem3.options.length= 0;
  document.forms[comparePhonesFormName].compareItem3.options[0]= new Option(default_model_option, "");

  var items = getDependentItems ( document.forms[comparePhonesFormName].selectManufacturer3.value );

  for (var i = 0; i < items.length; ++i) {

    var item = items[i];
    document.forms[comparePhonesFormName].compareItem3.options[i + 1] = new Option(item.name, item.idComboKey + ',' + item.image + ',' + item.description);
  }
}

///////////////////////////////////////////////////////////////////////////////
// Tariff Family/Tariff selection event handlers
///////////////////////////////////////////////////////////////////////////////

// reads compared tariffs informations from page URL and sets up apropriate items in listboxes.
function populateCompareTariffsItemsFromURL(default_option, separator)
{
    if (document.location.search == "" || document.location.search == 'undefined' || document.location.search.length <= 1 )
        return;

    var params = document.location.search.substr(1,document.location.search.length);
    var tariffIDs = new Array(3);
    tariffIDs[0] = getIdfromComposition(getURLParamValue(params,"compareItem1"), separator);
    tariffIDs[1] = getIdfromComposition(getURLParamValue(params,"compareItem1"), separator);
    tariffIDs[2] = getIdfromComposition(getURLParamValue(params,"compareItem1"), separator);

    for(var i = 0; i < tariffIDs.length; ++i) {
        if ( tariffIDs[i].length > 0 ) {
            for(var j = 0; j < i; ++j) {
               if ( tariffIDs[j].length == 0 ) {
                   tariffIDs[j] = tariffIDs[i];
                   tariffIDs[i] = "";
                   break;
               }
            }
        }
    }

    for(var tariffSelIdx = 1; tariffSelIdx <= 3; ++tariffSelIdx) {
        var curFamilySelect = document.getElementById("selectTariffFamily" + tariffSelIdx);
        var curTariffSelect = document.getElementById("compareItem" + tariffSelIdx);
        var tariffID = tariffIDs[tariffSelIdx-1];

        // if no tariff on current position
        if ( tariffID.length == 0 ) {
            curTariffSelect.options[0].selected = true;
            curFamilySelect.options[0].selected = true;
            continue;
        }

        for(var i = 0; i != curFamilySelect.options.length; ++i) {
            var curOption = curFamilySelect.options[i];

            if ( curOption.value.length == 0 )
                continue;

            var items = getDependentItems(curOption.value);
            for (var iItems = 0; iItems < items.length; ++iItems) {
                var item = items[iItems];
                var itemId = getIdfromComposition(item.idComboKey, separator);
                if ( itemId == tariffID ) {
                    curOption.selected = true;
                    eval("selectTariffFamilyOnChange" + tariffSelIdx + "('" + default_option + "');");
                    curTariffSelect.options[iItems+1].selected = true;
                    break;
                }
            }
       }
    }
}


//This function is used to update the values of the tariff select box on the tariffs compare page, when a new Tariff Family is selected
//
function selectTariffFamilyOnChange1(default_option) {

  document.CompareTariffsForm.compareItem1.options.length= 0;
  document.CompareTariffsForm.compareItem1.options[0]= new Option(default_option, "");

  var items = getDependentItems ( document.CompareTariffsForm.selectTariffFamily1.value );

  for (var i = 0; i < items.length; ++i) {

    var item = items[i];
    document.CompareTariffsForm.compareItem1.options[i + 1] = new Option(item.name, item.idComboKey);
  }
}
//This function is used to update the values of the tariff select box on the tariffs compare page, when a new Tariff Family is selected
//
function selectTariffFamilyOnChange2(default_option) {

  document.CompareTariffsForm.compareItem2.options.length= 0;
  document.CompareTariffsForm.compareItem2.options[0]= new Option(default_option, "");

  var items = getDependentItems ( document.CompareTariffsForm.selectTariffFamily2.value );

  for (var i = 0; i < items.length; ++i) {

    var item = items[i];
    document.CompareTariffsForm.compareItem2.options[i + 1] = new Option(item.name, item.idComboKey);
  }
}
//This function is used to update the values of the tariff select box on the tariffs compare page, when a new Tariff Family is selected
//
function selectTariffFamilyOnChange3(default_option) {

  document.CompareTariffsForm.compareItem3.options.length= 0;
  document.CompareTariffsForm.compareItem3.options[0]= new Option(default_option, "");

  var items = getDependentItems ( document.CompareTariffsForm.selectTariffFamily3.value );

  for (var i = 0; i < items.length; ++i) {

    var item = items[i];
    document.CompareTariffsForm.compareItem3.options[i + 1] = new Option(item.name, item.idComboKey);
  }
}

///////////////////////////////////////////////////////////////////////////////
// Selection event handler utilities
///////////////////////////////////////////////////////////////////////////////

// Function that expects a string of the form  id1,description1,,id2,description2,, ...
// Parses this string and returns an Array of Item objects that represent the items in the string.
//
function getDependentItems(inputString) {

  var toReturn = new Array();
  var pos = inputString.indexOf(SEP);

  var index = 0;

  while (pos != -1) {

    var name = inputString.substring(0, pos);

    inputString = inputString.substring(pos + 1);
    pos = inputString.indexOf(SEP);

    var idComboKey = inputString.substring(0, pos);
    inputString = inputString.substring(pos + 1);
    pos = inputString.indexOf(SEP);

    var image = inputString.substring(0, pos);
    inputString = inputString.substring(pos + 1);
    pos = inputString.indexOf(SEP);

    var description = inputString.substring(0, pos);
    inputString = inputString.substring(pos + 1);
    pos = inputString.indexOf(SEP);

    toReturn[index++] = new Item(name, idComboKey, image, description);

    inputString = inputString.substring(pos + 1);
    pos = inputString.indexOf(SEP);
  }
  return toReturn;
}

// function returns specified param from url
function getURLParamValue(url, paramName)
{
    var paramStart = url.indexOf(paramName);
    if ( paramStart == -1 )
        return "";
    var valueStart = paramStart + paramName.length + 1;
    var valueEnd = url.indexOf("&", valueStart);
    if ( valueEnd == -1 )
        valueEnd = url.length;

    return url.substr(valueStart, valueEnd - valueStart);
}

// function returns id part from id + separator + comboKey composition
function getIdfromComposition(inputString, separator) {
    var id = "";
    var pos = inputString.indexOf(separator);
    if (pos != -1){
        id = inputString.substring(0, pos);
    }
    return id;
}

// function returns comboKey part from id + separator + comboKey composition
function getComboKeyfromComposition(inputString, separator) {
    var comboKey = "";
    var pos = inputString.indexOf(separator);
    if (pos != -1){
        comboKey = inputString.substring(pos + separator.length);
    }
    return comboKey;
}

// Object representing a name, value pair.
//
function Item(name, idComboKey, image, description) {

  this.name = name;
  this.idComboKey = idComboKey;
  this.image = image;
  this.description = description;

  return this;
}

///////////////////////////////////////////////////////////////////////////////
// Compare functionality
///////////////////////////////////////////////////////////////////////////////

//   This provides convenience methods for working with cookies
//   document: The document object that the cookie is to be associated with
//   name:     Required name
//   path:     Optional - the path to be specified for the cookie
//   domain:   Optional - the domain to be specified for the cookie
//
function TCookie(document, name, path, domain)
{
    //alert ('Create cookie '+name);
    // All the predefined properties of this object begin with '$'
    // to distinguish them from other properties which are the values to
    // be stored in the cookie.
    this.$document = document;
    this.$name = name;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
}

// This function is the store() method of the TCookie object.
TCookie.prototype.store = function () {
    // First, loop through the properties of the TCookie object and
    // put together the value of the cookie. Since cookies use the
    // equals sign and semicolons as separators, we'll use colons
    // and ampersands for the individual state variables we store
    // within a single cookie value. Note that we escape the value
    // of each state variable, in case it contains punctuation or other
    // illegal characters.
    var cookieval = "";
    for(var prop in this) {
        // Ignore properties with names that begin with '$' and also methods.
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function'))
            continue;
        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + encodeURI(this[prop]);
    }

    // Now that we have the value of the cookie, put together the
    // complete cookie string, which includes the name and the various
    // attributes specified when the TCookie object was created.
    var cookie = this.$name + '=' + cookieval;
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    // alert ('Store cookie '+cookie);

    // Now store the cookie in document specified during cookie creation
    this.$document.cookie = cookie;
}

// This function is the load() method of the TCookie object.
TCookie.prototype.load = function() {
    //alert ('Load cookie '+this.$name);
    // First, get a list of all cookies that pertain to this document.
    // We do this by reading the magic Document.cookie property.
    var allcookies = this.$document.cookie;
    if (allcookies == "") return false;

    // Now extract just the named cookie from that list.
    var start = allcookies.indexOf(this.$name + '=');
    if (start == -1) return false;   // TCookie not defined for this page.
    start += this.$name.length + 1;  // Skip name and equals sign.
    var end = allcookies.indexOf(';', start);
    if (end == -1) end = allcookies.length;
    var cookieval = allcookies.substring(start, end);

    // Now that we've extracted the value of the named cookie, we've
    // got to break that value down into individual state variable
    // names and values. The name/value pairs are separated from each
    // other by ampersands, and the individual names and values are
    // separated from each other by colons. We use the split method
    // to parse everything.
    var a = cookieval.split('&');    // Break it into array of name/value pairs.
    for(var i=0; i < a.length; i++)  // Break each pair into an array.
        a[i] = a[i].split(':');

    for(var i = 0; i < a.length; i++) {
        this[a[i][0]] = unescape(a[i][1]);
    }

    return true;
}

// This function is the remove() method of the TCookie object.
TCookie.prototype.remove = function() {
    //alert ('Remove cookie '+this.$name);
    var cookie;
    cookie = this.$name + '=';
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

    this.$document.cookie = cookie;
}

//This function will add an item to the compare list
//It requires an identifier for the item which will be submitted in the form post for the server
//side processing of the comparison.
//A location of the image for the comparable item also needs to be supplied
//The last parameter addThisItem is a boolean indicating whether this item is to be added (true)
// or removed (false) and is determined by whether the checkbox is checked or not

var noPhoneImgLocation = '/eshop/content/personal/common/compare_phones.gif';
var noDatacardImgLocation = '/eshop/content/personal/common/compare_datacards.gif';

function addRemoveComparableItem(addThisItem, identifier, location, description) {


  if (itemType=='phone') {

	 if (addThisItem == true) { //if this is true the item needs to be added to list of comparables

		if (visitorCookie.id1 == '' || visitorCookie.id1 == null || visitorCookie.id1 == 'undefined') {
		  setFirstItem(identifier, location, description);
		}
		else if (visitorCookie.id2 == '' || visitorCookie.id2 == null || visitorCookie.id2 == 'undefined') {
		  setSecondItem(identifier, location, description);
		}
		else if (visitorCookie.id3 == '' || visitorCookie.id3 == null || visitorCookie.id3 == 'undefined') {
		  setThirdItem(identifier, location, description);
		}
		else { //okay if the third item is full we need to make the newly selected item the third item and push the others down
		  setFirstItem(visitorCookie.id2, visitorCookie.im2, visitorCookie.d2);
		  setSecondItem(visitorCookie.id3, visitorCookie.im3, visitorCookie.d3);
		  setThirdItem(identifier, location, description);
		  populateAvailableItemsFormFromCookie();
		}
	  }
	  else { // addThisItem == false, so we must remove this item for comparison

		if (visitorCookie.id1 == identifier) {
		  setFirstItem(visitorCookie.id2, visitorCookie.im2, visitorCookie.d2);
		  setSecondItem(visitorCookie.id3, visitorCookie.im3, visitorCookie.d3);
		  setThirdItem('', noPhoneImgLocation, '');
		}

		else if (visitorCookie.id2 == identifier) {
		  setSecondItem(visitorCookie.id3, visitorCookie.im3, visitorCookie.d3);
		  setThirdItem('',noPhoneImgLocation, '');
		}

		else if (visitorCookie.id3 == identifier) {
		  setThirdItem('',noPhoneImgLocation, '');
		}
	  }
  }
  else if (itemType=='datacard'){

      if (addThisItem == true) { //if this is true the item needs to be added to list of comparables

         if (visitorCookie.id1 == '' || visitorCookie.id1 == null || visitorCookie.id1 == 'undefined') {
           setFirstItem(identifier, location, description);
         }
         else if (visitorCookie.id2 == '' || visitorCookie.id2 == null || visitorCookie.id2 == 'undefined') {
           setSecondItem(identifier, location, description);
         }
         else if (visitorCookie.id3 == '' || visitorCookie.id3 == null || visitorCookie.id3 == 'undefined') {
           setThirdItem(identifier, location, description);
         }
         else { //okay if the third item is full we need to make the newly selected item the third item and push the others down
           setFirstItem(visitorCookie.id2, visitorCookie.im2, visitorCookie.d2);
           setSecondItem(visitorCookie.id3, visitorCookie.im3, visitorCookie.d3);
           setThirdItem(identifier, location, description);
           populateAvailableItemsFormFromCookie();
         }
       }
       else { // addThisItem == false, so we must remove this item for comparison

         if (visitorCookie.id1 == identifier) {
           setFirstItem(visitorCookie.id2, visitorCookie.im2, visitorCookie.d2);
           setSecondItem(visitorCookie.id3, visitorCookie.im3, visitorCookie.d3);
           setThirdItem('',noDatacardImgLocation, '');
         }

         else if (visitorCookie.id2 == identifier) {
           setSecondItem(visitorCookie.id3, visitorCookie.im3, visitorCookie.d3);
           setThirdItem('',noDatacardImgLocation, '');
         }

         else if (visitorCookie.id3 == identifier) {
           setThirdItem('',noDatacardImgLocation, '');
         }
       }
  }
  else if (itemType=='tariff') {
	 if (addThisItem == true) { //if this is true the item needs to be added to list of comparables

		if (visitorCookie.plan1Identifier == '' || visitorCookie.plan1Identifier == null || visitorCookie.plan1Identifier == 'undefined') {
		  setFirstItem(identifier, '', '');
		}
		else if (visitorCookie.plan2Identifier == '' || visitorCookie.plan2Identifier == null || visitorCookie.plan2Identifier == 'undefined') {
		  setSecondItem(identifier, '', '');
		}
		else { //okay if the second item is full we need to make the newly selected item the second item and push the others down
		  setFirstItem(visitorCookie.plan2Identifier, '', '');
		  setSecondItem(identifier, '', '');
		  populateAvailableItemsFormFromCookie();
		}
	  }
	  else { // addThisItem == false, so we must remove this item for comparison
		if (visitorCookie.plan1Identifier == identifier) {
		  setFirstItem(visitorCookie.plan2Identifier, '', '');
		  setSecondItem('','', '');
		}

		else if (visitorCookie.plan2Identifier == identifier) {
		  setSecondItem('','', '');
		}

	  }
  }
  else {
    alert('Undefined itemType in addRemoveComparableItem() method. itemType='+itemType);
  }


}

// specify identifier, image location and display text for this item

function setFirstItem(identifier, imageLocation, description) {

  if (itemType=='phone') {

      if (imageLocation == '' || imageLocation == null || imageLocation == 'undefined') {
        document.forms[comparePhonesFormName].image1.src = noPhoneImgLocation;
        document.forms[comparePhonesFormName].image1.alt = 'Default phone image';  
        document.forms[comparePhonesFormName].image1.title = 'Add phone to compare';
      } else {
        document.forms[comparePhonesFormName].image1.src = imageLocation;
        document.forms[comparePhonesFormName].image1.alt = description;
        document.forms[comparePhonesFormName].image1.title = description;
      }
      document.forms[comparePhonesFormName].compareItem1.value = identifier;
      document.forms[comparePhonesFormName].removeItem1CheckBox.checked=(identifier != '' && identifier != null && identifier!='undefined');
      if ( document.forms[productFormName] != null && document.forms[productFormName] != 'undefined' )
        //productListForm.compareItem1.value = identifier;
      visitorCookie.im1=imageLocation;
      visitorCookie.id1=identifier;
      visitorCookie.d1 = description;
      /*if (displayText == null || displayText == 'undefined') {
        document.forms[comparePhonesFormName].item1DisplayText.value='';
        visitorCookie.item1DisplayText='';
      } else {
        document.forms[comparePhonesFormName].item1DisplayText.value = displayText;
        document.forms[comparePhonesFormName].item1DisplayText.disabled = true;
        visitorCookie.item1DisplayText=displayText;
      }*/
      visitorCookie.store();
  }
  else if (itemType == 'datacard'){

      if (imageLocation == '' || imageLocation == null || imageLocation == 'undefined') {
        document.forms[comparePhonesFormName].image1.src = noDatacardImgLocation;
        document.forms[comparePhonesFormName].image1.alt = '';
        document.forms[comparePhonesFormName].image1.title = '';
      } else {
        document.forms[comparePhonesFormName].image1.src = imageLocation;
        document.forms[comparePhonesFormName].image1.alt = description;
        document.forms[comparePhonesFormName].image1.title = description;
      }
      document.forms[comparePhonesFormName].compareItem1.value = identifier;
      document.forms[comparePhonesFormName].removeItem1CheckBox.checked=(identifier != '' && identifier != null && identifier!='undefined');
      if ( document.forms[productFormName] != null && document.forms[productFormName] != 'undefined' )
      visitorCookie.im1=imageLocation;
      visitorCookie.id1=identifier;
      visitorCookie.d1 = description;
      visitorCookie.store();
  }
  else if (itemType=='tariff') {
      document.forms[comparePhonesFormName].selectPlan1.value = identifier;
      //document.forms[comparePhonesFormName].removeItem1CheckBox.checked=(identifier != '' && identifier != null && identifier!='undefined');
      //productListForm.selectPlan1.value = identifier;
      visitorCookie.plan1Location=imageLocation;
      visitorCookie.plan1Identifier=identifier;
      /*if (displayText == null || displayText == 'undefined') {
        document.forms[comparePhonesFormName].item1DisplayText.value='';
        visitorCookie.plan1DisplayText='';
      } else {
        document.forms[comparePhonesFormName].item1DisplayText.value = displayText;
        visitorCookie.plan1DisplayText=displayText;
      } */
      visitorCookie.store();
  }
  else {
    alert('Undefined itemType in setFirstItem() method. itemType='+itemType);
  }



}

// specify identifier, image location and display text for this item

function setSecondItem(identifier, imageLocation, description) {


  if (itemType=='phone') {

      if (imageLocation == '' || imageLocation == null || imageLocation == 'undefined') {
        document.forms[comparePhonesFormName].image2.src = noPhoneImgLocation;
        document.forms[comparePhonesFormName].image2.alt = 'Default phone image';
        document.forms[comparePhonesFormName].image2.title = 'Add phone to compare';
      } else {
        document.forms[comparePhonesFormName].image2.src = imageLocation;
        document.forms[comparePhonesFormName].image2.alt = description;
        document.forms[comparePhonesFormName].image2.title = description;
      }
      document.forms[comparePhonesFormName].compareItem2.value = identifier;
      document.forms[comparePhonesFormName].removeItem2CheckBox.checked=(identifier != '' && identifier != null && identifier!='undefined');
      if ( document.forms[productFormName] != null && document.forms[productFormName] != 'undefined' )
        //productListForm.compareItem2.value = identifier;
      visitorCookie.im2=imageLocation;
      visitorCookie.id2=identifier;
      visitorCookie.d2=description;
      /*if (displayText == null || displayText == 'undefined') {
        document.forms[comparePhonesFormName].item2DisplayText.value='';
        visitorCookie.item2DisplayText='';
      } else {
        document.forms[comparePhonesFormName].item2DisplayText.value = displayText;
        document.forms[comparePhonesFormName].item2DisplayText.disabled = true;
        visitorCookie.item2DisplayText=displayText;
      } */
      visitorCookie.store();
  }
  else if (itemType=='datacard'){
      if (imageLocation == '' || imageLocation == null || imageLocation == 'undefined') {
        document.forms[comparePhonesFormName].image2.src = noDatacardImgLocation;
        document.forms[comparePhonesFormName].image2.alt = '';
        document.forms[comparePhonesFormName].image2.title = '';
      } else {
        document.forms[comparePhonesFormName].image2.src = imageLocation;
        document.forms[comparePhonesFormName].image2.alt = description;
        document.forms[comparePhonesFormName].image2.title = description;
      }
      document.forms[comparePhonesFormName].compareItem2.value = identifier;
      document.forms[comparePhonesFormName].removeItem2CheckBox.checked=(identifier != '' && identifier != null && identifier!='undefined');
      if ( document.forms[productFormName] != null && document.forms[productFormName] != 'undefined' )
      visitorCookie.im2=imageLocation;
      visitorCookie.id2=identifier;
      visitorCookie.d2=description;
      visitorCookie.store();
  }
  else if (itemType=='tariff') {
      document.forms[comparePhonesFormName].selectPlan2.value = identifier;
      //document.forms[comparePhonesFormName].removeItem2CheckBox.checked=(identifier != '' && identifier != null && identifier!='undefined');
      //productListForm.selectPlan2.value = identifier;
      visitorCookie.plan2Identifier=identifier;
      /*if (displayText == null || displayText == 'undefined') {
        document.forms[comparePhonesFormName].item2DisplayText.value='';
        visitorCookie.plan2DisplayText='';
      } else {
        document.forms[comparePhonesFormName].item2DisplayText.value = displayText;
        visitorCookie.plan2DisplayText=displayText;
      } */
      visitorCookie.store();
  }
  else {
    alert('Undefined itemType in setSecondItem() method. itemType='+itemType);
  }


}



// specify identifier, image location and display text for this item

function setThirdItem(identifier, imageLocation, description) {

  if (itemType=='phone') {

      if (imageLocation == '' || imageLocation == null || imageLocation == 'undefined') {
        document.forms[comparePhonesFormName].image3.src = noPhoneImgLocation;
        document.forms[comparePhonesFormName].image3.alt = 'Default phone image';
        document.forms[comparePhonesFormName].image3.title = 'Add phone to compare';
      } else {
        document.forms[comparePhonesFormName].image3.src = imageLocation;
        document.forms[comparePhonesFormName].image3.alt = description;
        document.forms[comparePhonesFormName].image3.title = description;
      }
      document.forms[comparePhonesFormName].compareItem3.value = identifier;
      document.forms[comparePhonesFormName].removeItem3CheckBox.checked=(identifier != '' && identifier != null && identifier!='undefined');
      if ( document.forms[productFormName] != null && document.forms[productFormName] != 'undefined' )
        //productListForm.compareItem3.value = identifier;
      visitorCookie.im3=imageLocation;
      visitorCookie.id3=identifier;
      visitorCookie.d3=description;
      /*if (displayText == null || displayText == 'undefined') {
        document.forms[comparePhonesFormName].item3DisplayText.value='';
        visitorCookie.item3DisplayText='';
      } else {
        document.forms[comparePhonesFormName].item3DisplayText.value = displayText;
        document.forms[comparePhonesFormName].item3DisplayText.disabled = true;
        visitorCookie.item3DisplayText=displayText;
      } */
      visitorCookie.store();
  }
  else if (itemType=='datacard'){
      if (imageLocation == '' || imageLocation == null || imageLocation == 'undefined') {
        document.forms[comparePhonesFormName].image3.src = noDatacardImgLocation;
        document.forms[comparePhonesFormName].image3.alt = '';
        document.forms[comparePhonesFormName].image3.title = '';
      } else {
        document.forms[comparePhonesFormName].image3.src = imageLocation;
        document.forms[comparePhonesFormName].image3.alt = description;
        document.forms[comparePhonesFormName].image3.title = description;
      }
      document.forms[comparePhonesFormName].compareItem3.value = identifier;
      document.forms[comparePhonesFormName].removeItem3CheckBox.checked=(identifier != '' && identifier != null && identifier!='undefined');
      if ( document.forms[productFormName] != null && document.forms[productFormName] != 'undefined' )
      visitorCookie.im3=imageLocation;
      visitorCookie.id3=identifier;
      visitorCookie.d3=description;
      visitorCookie.store();
  }
  else if (itemType=='tariff') {

     alert('The setThirdItem method has been called with an itemType of plan. only two plans can be compared!');
  }
  else {
    alert('Undefined itemType in setThirdItem() method. itemType='+itemType);
  }


}

//This function is used to update the values of the item1, item2 and item3 variables from the values
//stored in the cookie as well as setting the image sources for the images boxes in the CompareMaterialProductsForm form


function populateCompareFormFromCookie() {

  if (itemType=='phone' || itemType == 'datacard') {
	  setFirstItem(visitorCookie.id1, visitorCookie.im1, visitorCookie.d1);
	  setSecondItem(visitorCookie.id2, visitorCookie.im2, visitorCookie.d2);
	  setThirdItem(visitorCookie.id3, visitorCookie.im3, visitorCookie.d3);
  }
  else if (itemType=='tariff') {
	  setFirstItem(visitorCookie.plan1Identifier, '', '');
	  setSecondItem(visitorCookie.plan2Identifier, '', '');
  }
  else {
    alert('Undefined itemType in populateCompareFormFromCookie() method. itemType='+itemType);
  }
}

function populateAvailableItemsFormFromCookie() {


  /*if ( document.forms[comparePhonesFormName] != null && typeof(document.forms[comparePhonesFormName]) != 'undefined' ) {
    if ( document.forms[comparePhonesFormName].item1DisplayText != null && typeof(document.forms[comparePhonesFormName].item1DisplayText) != 'undefined' ) {
        document.forms[comparePhonesFormName].item1DisplayText.disabled = true;
        document.forms[comparePhonesFormName].item2DisplayText.disabled = true;
        document.forms[comparePhonesFormName].item3DisplayText.disabled = true;
    }
  } */

  if (itemType=='phone' || itemType == 'datacard') {

    if ( document.forms[productFormName] != null && typeof(document.forms[productFormName]) != 'undefined' ) {
        var formElements = document.forms[productFormName].elements;
	    for (var count = 0; count < formElements.length; count++) {
		    var formElement = formElements[count];
            if (formElement.type == "checkbox" && formElement.id.substring(0,8) == "compare-") {
                if (formElement.name == visitorCookie.id1 || formElement.name == visitorCookie.id2 || formElement.name == visitorCookie.id3) {
			        formElement.checked=true;
		        } else {
			        formElement.checked=false;
		        }
		    }
	    }
    }

	  //productListForm.compareItem1.value = visitorCookie.id1;
	  //productListForm.compareItem2.value = visitorCookie.id2;
	  //productListForm.compareItem3.value = visitorCookie.id3;
  }
  else if (itemType=='tariff') {
    for (var docForms=0; docForms<document.forms.length; docForms++) {
      if (document.forms[docForms].name == "CompareMaterialProductsForm") {
        continue;
      }
	  var formElements = document.forms[docForms].elements;
	  for (var count = 0; count < formElements.length; count++) {
		var formElement = formElements[count];
        if (formElement.type == "checkbox" && formElement.id.substring(0,8) == "compare-") {
		  if (formElement.name == visitorCookie.plan1Identifier || formElement.name == visitorCookie.plan2Identifier ) {
			formElement.checked=true;
		  }
		  else {
			formElement.checked=false;
		  }
		}
	  }
	}

	  //productListForm.selectPlan1.value = visitorCookie.plan1Identifier;
	  //productListForm.selectPlan2.value = visitorCookie.plan2Identifier;
  }
  else {
    alert('Undefined itemType in populateAvailableItemsFormFromCookie() method. itemType='+itemType);
  }

}

// ***** Additional part *****

// Adds function to window 'onload' sequence
function addOnload(functObj) {
    var oldOnLoad = window.onload;
    window.onload = (oldOnLoad) ? function() {functObj(); oldOnLoad()} : functObj;
}

function clearCookie () {
    //alert ('clear cookies');
    var visitorCookie = new TCookie(document, 'visitorCookie', '/');
    visitorCookie.load();

    visitorCookie.id1 = '';
    visitorCookie.im1 = '';
    visitorCookie.d1 = '';
    visitorCookie.id2 = '';
    visitorCookie.im2 = '';
    visitorCookie.d2 = '';
    visitorCookie.id3 = '';
    visitorCookie.im3 = '';
    visitorCookie.d3 = '';

    visitorCookie.store();
}

function setVisitorCookie(mpc, image, description) {
    var visitorCookie = new TCookie(document, 'visitorCookie', '/');
    visitorCookie.load();
    if (visitorCookie.id1 == '' || visitorCookie.id1 == null || visitorCookie.id1 == 'undefined') {
        visitorCookie.id1 = mpc;
        visitorCookie.im1 = image;
        visitorCookie.d1 = description;
    }
    else if (visitorCookie.id2 == '' || visitorCookie.id2 == null || visitorCookie.id2 == 'undefined') {
        visitorCookie.id2 = mpc;
        visitorCookie.im2 = image;
        visitorCookie.d2 = description;
    }
    else if (visitorCookie.id3 == '' || visitorCookie.id3 == null || visitorCookie.id3 == 'undefined') {
        visitorCookie.id3 = mpc;
        visitorCookie.im3 = image;
        visitorCookie.d3 = description;
    }

    visitorCookie.store();
}

// if payment type has changed - clear visitorCookie and save new payment type
function checkPaymentType(currentPaymentType, isPersonal) {
//    alert('Payment type from cookie="'+visitorCookie.pT+'", current payment type="'+currentPaymentType+'", \npersonal from cookie="'+ visitorCookie.pers+'", current personal="'+isPersonal+'"');
    if (visitorCookie.pT != currentPaymentType || visitorCookie.pers != isPersonal) {
        clearCookie();
        visitorCookie = new TCookie(document, 'visitorCookie', '/');
        visitorCookie.load();
        visitorCookie.pT = currentPaymentType;
        visitorCookie.pers = isPersonal;
        visitorCookie.store();
        return false;
    }
    return true;
}

//Method is used to enable/disable checkout confirmation popup cookie
function setCheckoutConfirmationPopup(flag){
	if (updateCheckoutCookie) {
		var cState = new TCookie(document, 'cState', '/');
		cState.load();
		if(flag){
			cState.popup = "1";
		} else {
			cState.popup = "0";
		}
		cState.store();
	}
};


function setCookieToRemovePackage(packageId, reload) {
    var removePackageCookie = new TCookie(document, 'removePackageCookie', '/');
    removePackageCookie.removePackageId = packageId;
    removePackageCookie.store();
    if (reload) {
        window.location.reload(true);
    }
}

//
// Sets updateCookie flag. True - if cState cookie could be upated, false - otherwise.
//
function setUpdateCheckoutCookie(flag) {
	updateCheckoutCookie = flag;
}

//
// Uses to reset cState cookie flags.
//
function resetCheckoutCookie() {
	var cState = new TCookie(document, 'cState', '/');
	cState.load();
	cState.started = "0";
	cState.popup = "0";
	cState.store();
}
function changeMessageBoxMessage(text) {
    var messageBox = document.getElementById("messageBox");
    if (messageBox != undefined) {
        messageBox.innerHTML = text;
    }
}

function popupView(url, width, height) {
	var WINDOW_FEATURES = 'location=0, statusbar=0, menubar=0, scrollbars=1';
	var theWindow = window.open(url, '_blank', WINDOW_FEATURES + 'width=' + width + ', height=' + height);
	theWindow.focus();
	return theWindow;
}

function changeSpanText(id, text) {
    var span = document.getElementById(id);
    if (span) {
        span.innerHTML = text;
        window.changedSpan = span;
    }
}

function restoreSpanText() {
    if (window.changedSpan) {
        window.changedSpan.innerHTML = '';
        window.changeSpan = null;
    }
}

var _queue = _queue || [];

_queue.push(['General',function(){

function hideAddToCardLink(id) {
    if ($(id)) {
        $(id).hide();
        window.changedLink = id;
    }
}

function showAddToCardLink() {
    if ($(window.changedLink)) {
        $(window.changedLink).show();
    }
}

function hideElement(id) {
    if ($(id)) {
        $(id).hide();
    }
}

function showElement(id) {
    if ($(id)) {
        $(id).show();
    }
}


}])


