
/** Request Parameters*/
var URLPARAM_UISTATE = "uistate";
var URLPARAM_LOCALE = "locale";
var URLPARAM_CONFIGURATION = "conf";
var URLPARAM_PATH = "path";
var URLPARAM_STYLE = "style";
var URLPARAM_PRODUCT_CODE = "product_code";

/**
 * Given an HTML element id, it references it and changes the style class with
 * the provided one.
 *
 * id - HTML element id. classname - New CSS class name.
 */
function changeStyle(id, classname) {
    document.getElementById(id).className = classname;
}

/**
 * Generic JS function, used to load a AJAX request in a target HTML element
 * provided by it's id (targetElementId). An optional callback function can also
 * be provided, that will be called after the response arrives and has a
 * signature like: (responseText, textStatus, XMLHttpRequest).
 *
 * url - the GET url to request; targetElementId - the target HTML elemet (where
 * the response will be written with .innerHTML) callbackFunction - optional
 * function to be called after the response is provided by the server.
 */
function ajaxLoadUrl(url, targetElementId, callbackFunction) {
    if (url == null) {
        alert("Invalid call: ajaxLoadUrl(), url should not be null!");
        return;
    }
    if (targetElementId == null) {
        alert("Invalid call: ajaxLoadUrl(), targetElementId should not be null!");
        return;
    }
    $("#" + targetElementId).load(url, null,
        function(responseText, textStatus, XMLHttpRequest){
            if (callbackFunction != null) {
                callbackFunction(responseText, textStatus, XMLHttpRequest);
            }
        }
    );
}

/** State describing if a new tab load is possible. */
var tabLoadingEnabled = true;

/** Make new tab load possible. */
function enableTabLoading() {
    tabLoadingEnabled = true;
    var overlayPreloader = document.getElementById("overlay_preloader");
    overlayPreloader.style.visibility = "hidden";
}

/** Make new tab load not possible. */
function disableTabLoading() {
    tabLoadingEnabled = false;
}

/** Returns true if a new tab load is possible. */
function isTabLoadingEnabled() {
    return tabLoadingEnabled;
}
/**
 * Used to load a Product or Family tab with AJAX. Will call the
 * ajaxLoadUrl(url, targetElementId, callbackFunction) with appropriate params.
 * It also assures Graphical tab change after the request/response is done.
 *
 * bodyUrl - The GET url to request body content; tabUrl - The GET url to
 * request tab ui contents;
 */
function ajaxLoadTab(bodyUrl, tabUrl) {
    // Prevents the user to skip tab loading and call another one before the
    // first call finished.
    if (!isTabLoadingEnabled()) {
        return;
    }
    disableTabLoading();

    var loadTabTarget = document.getElementById("body_content_left");
    loadTabTarget.innerHTML = "<div class='content_left_frame clearfix'>" +
        "<div class='content_left_spacer'></div>" +
        "<div class='content_left'></div>" +
        "</div><div class='content_left_bottom'></div>";

    var overlayPreloader = document.getElementById("overlay_preloader");
    overlayPreloader.style.visibility = "visible";

    // Call ajax generic function, loads url in target.
    ajaxLoadUrl(bodyUrl, "body_content_left", enableTabLoading);
    ajaxLoadUrl(tabUrl, "body_tabs");
}

/** Displays in an alert, the AJAX response. */
function debugAjaxResponse(responseText, textStatus, XMLHttpRequest) {
    alert("\ttextStatus:\n" + textStatus + "\n\tresponseText:\n" + responseText);
}

/**
 * Ajax load search in overlay.
 */
function ajaxLoadSearchOverlay(urlSearch) {
    var searchString = document.getElementById('search').value;
    var url = urlSearch+'&search=' + escape(searchString);
    $("#overlay_content").load(url, null,
        function(responseText, textStatus, XMLHttpRequest){
          if (responseText.indexOf("REDIRECT") <= 0) {
            var overlayDiv = document.getElementById("overlay");
            overlayDiv.style.visibility = "visible";
            var searchFrameDiv = document.getElementById("overlay_content");
            searchFrameDiv.style.visibility = "visible";
          }
        }
    );
}

/**
 * Load the cart overlay with a given page number
 */
function ajaxLoadCartOverlay(targetUrl) {
	var urlSeparator = targetUrl.indexOf("?") < 0 ? "?" : "&";
	var targetUrlNoCache = targetUrl + urlSeparator +"rand=" + Math.random();
    $("#overlay_content").load(targetUrlNoCache, null,
        function(responseText, textStatus, XMLHttpRequest){
            var overlayDiv = document.getElementById("overlay");
            overlayDiv.style.visibility = "visible";
            var searchFrameDiv = document.getElementById("overlay_content");
            searchFrameDiv.style.visibility = "visible";
        }
    );
}

/**
    Loads the overlay configurator and passes the tab selection
    from an input type hidden named: "tab_number_ajax".
    "tab_number_ajax" hidden input will be filled/changed by each ajax load of a tab.
 */
function ajaxLoadOverlayConfigurator(targetUrl) {
    var uistateVal = 0;
    var tabNrInput = document.getElementById("tab_number_ajax");
    if (tabNrInput != null){
        var tabNrInputVal = tabNrInput.value;
        if(tabNrInputVal != null && tabNrInputVal.split(" ").join("") != "" ){
            uistateVal = tabNrInputVal;
        }
    }
    var url = targetUrl + "&" + URLPARAM_UISTATE + "=" +  uistateVal;
    ajaxLoadOverlay(url);
}

/**
	Loads the overlay configurator and passes product_code to search
*/
function ajaxLoadOverlayProductSearch(targetUrl) {
	var codeInput = document.getElementById("product_code_input");
	var code = jQuery.trim(codeInput.value);
	var url = targetUrl + "&" + URLPARAM_PRODUCT_CODE + "=" +  code;
	ajaxLoadOverlay(url);
}

/**
 * Load an overlay with a given target url
 */
function ajaxLoadOverlay(targetUrl) {
  $("#overlay_content").load(targetUrl, null,
    function(responseText, textStatus, XMLHttpRequest){
      var overlayDiv = document.getElementById("overlay");
      overlayDiv.style.visibility = "visible";
      var searchFrameDiv = document.getElementById("overlay_content");
      searchFrameDiv.style.visibility = "visible";
    }
  );
}

/**
    Closes the overlay div, set visibility hidden.
 */
function closeOverlay() {
    var overlayDiv = document.getElementById("overlay");
    overlayDiv.style.visibility = "hidden";
    var searchFrameDiv = document.getElementById("overlay_content");
    searchFrameDiv.innerHTML = "";
    searchFrameDiv.style.visibility = "hidden";
}

/**
 * Handles the return key press when search input is in focus.
 */
function handleSearchGoKeyPress(event) {
    if (event == null) {
        event = window.event;
    }
    var keynum = 0;
    if(window.event) { // IE
      keynum = event.keyCode;
    } else if(event.which) { // Netscape/Firefox/Opera
      keynum = event.which;
    }
    if (keynum == 13) {
        var searchButton = document.getElementById("searchButton");
        eval(searchButton.onclick)();
    }
}

/**
 * //TODO cristi 19.12.2008
 *
 * @responsible person: document this function.
 */
//function verifyCaptcha(contactUrl) {
//  var captcha = document.getElementById("captcha_text");
//  var message_type = document.getElementById("type");
//  var type = message_type.options[message_type.selectedIndex];
//  var email = document.getElementById("email");
//  var message = document.getElementById("message");
//  $("#contact_messages").load(contactUrl, {captcha : captcha.value,
//                                                          type : type.value,
//                                                          email : email.value,
//                                                          message : message.value,
//                                                          current_location : document.location.href
//                                                         },
//    function(responseText, textStatus, XMLHttpRequest) {
//      var messagesDiv = document.getElementById("contact_messages");
//      var trimmed = responseText.replace(/^\s*/, '');
//      if (trimmed == "") {
//        closeOverlay();
//      } else {
//        messagesDiv.style.visibility = "visible";
//        captcha.value="";
//      }
//    }
//  );
//}
 
 function verifyCaptcha(contactUrl) {
	  var formData = $("#formContact").serialize();
	  $.post(contactUrl, formData, 
			  function(data) {
				  var trimmed = data.replace(/^\s*/, '');
			      if (trimmed == "") {
			        closeOverlay();
			      } else {
			    	  $("#contact_messages").html(data);
			      }
	  		  }); 
	}

function verifyCaptchaSendRequestDialog(sendUrl) {
	var formData = $("#requestForm").serialize();
	$.post(sendUrl, formData, function(data){
		var trimmed = data.replace(/^\s*/, '');
	      if (trimmed == "") {
	        closeOverlay();
	      } else {
	    	  $("#contact_messages").html(data);
	      }
	});
}

//function verifyCaptchaSendRequestDialog(sendUrl) {
//  var captcha = document.getElementById("captcha_text");
//  var email = document.getElementById("email");
//  var message = document.getElementById("message");
//   $("#contact_messages").load(sendUrl, {captcha : captcha.value,
//                                                          email : email.value,
//                                                          message : message.value
//                                                         },
//    function(responseText, textStatus, XMLHttpRequest) {
//      var messagesDiv = document.getElementById("contact_messages");
//      var trimmed = responseText.replace(/^\s*/, '');
//      if (trimmed == "") {
//        closeOverlay();
//      } else {
//        messagesDiv.style.visibility = "visible";
//        captcha.value="";
//      }
//    }
//  );
//}


/**
 * Verifies the Captcha for send products overlay dialog.
 */
function verifyCaptchaSendProductsDialog(sendUrl) {
    var captcha = document.getElementById("captcha_text");
    var emailTo = document.getElementById("emailTo");
    var emailFrom = document.getElementById("emailFrom");
    var message = document.getElementById("message");
    $("#contact_messages").load(sendUrl, {captcha : captcha.value,
                                          emailTo : emailTo.value,
                                          emailFrom : emailFrom.value,
                                          message : message.value
                                          },
    function(responseText, textStatus, XMLHttpRequest) {
       var messagesDiv = document.getElementById("contact_messages");
       var trimmed = responseText.replace(/^\s*/, '');
       if (trimmed == "") {
           closeOverlay();
       } else {
           messagesDiv.style.visibility = "visible";
           captcha.value="";
       }
     }
   );
}

/**
    Makes another call to captcha servlet.
 */
function reloadCaptcha(imgUrl) {
    var imgEl = document.getElementById("captcha_image");
    imgEl.src = imgUrl + "?cache=" + Math.random();
}

/**
 * Loads the configuration attempt in the overlay_content. The request contains
 * the current particle with it's original value. All particle values are sent
 * to the server.
 */
function ajaxLoadConfiguratorValidation(urlConfiguration, selectElement) {
    var url = urlConfiguration;
    if (selectElement != null)
	{
    	var currentParticle = selectElement.id;
    	url += "&current_particle=" + currentParticle;
    	var originalValue = document.getElementById("selected_value_" + selectElement.id).value;
        url += "&original_value=" + originalValue;
	}
    else
    {
    	url += "&current_particle=&autoforward=false";
    }
    
    var configurationForm = document.getElementById("formConfigurator");
    var selectElements = configurationForm.getElementsByTagName("select");

    for (var i = 0; i < selectElements.length; i++) {
        var tmpSelect = selectElements[i];
        var tmpSelectId = tmpSelect.id;
        var tmpSelectValue = tmpSelect.options[tmpSelect.selectedIndex].value;
        url += "&" + tmpSelectId + "=" + tmpSelectValue;
    }

    // Disables apply button until configurator is reloaded. Prevents user to
    // cheat.
    var buttonApply = document.getElementById("button_configurator_apply");
    if (buttonApply != null) {
        buttonApply.href = "#";
    }

    // Ajax call.
    $("#overlay_content").load(url, null,
        function(responseText, textStatus, XMLHttpRequest){
            // Place focus on the current particle.
            var currentParticleNameInput = document.getElementById("currentParticle");
            var currentParticleName = null;
            if (currentParticleNameInput != null) {
               currentParticleName = currentParticleNameInput.value;
            }
            var currentParticleSelect = document.getElementById(currentParticleName);
            if (currentParticleSelect != null) {
                currentParticleSelect.focus();
            }
        }
    );
}

/**
 * Starts the call that adds a product to the shopping cart and refreshes the
 * label in the header.
 */
function ajaxAddProductToCart(urlAdd) {
  urlAdd += "&cache=" + Math.random();
  $("#header_cart_span").load(urlAdd, null,
         function(responseText, textStatus, XMLHttpRequest){
        }
  );
}

/**
 * Clears the shopping cart.
 */
function ajaxClearCart(urlClearCart, urlRefreshCart) {
  urlClearCart += "?cache=" + Math.random();
  urlRefreshCart += "?cache=" + Math.random();
  $("#overlay_content").load(urlClearCart, null,
     function(responseText, textStatus, XMLHttpRequest){
       $("#header_cart_span").load(urlRefreshCart, null,
         function(responseText, textStatus, XMLHttpRequest){
         }
         );
     }
  );
}

/**
 * Removes a product from the shopping cart.
 */
function ajaxRemoveProduct(urlRemoveProduct, urlRefreshCart) {
  urlRefreshCart += "?cache=" + Math.random();
  $("#overlay_content").load(urlRemoveProduct, null,
     function(responseText, textStatus, XMLHttpRequest){
       $("#header_cart_span").load(urlRefreshCart, null,
         function(responseText, textStatus, XMLHttpRequest){
         }
         );
     }
  );
}

/**
 * Removes a product from the shopping cart.
 */
function ajaxRefreshCart(urlUpdateQuant, urlRefreshCart) {
  var numberOfElements = document.getElementById("number_of_elements").value;
  var params = {};
  params['number_of_elements']=numberOfElements;
  for (i = 0; i < numberOfElements; i++) {
    var quantity = document.getElementById('obj_' + i + '_quant').value;
    var path = document.getElementById('obj_' + i + '_path').value;
    var conf = document.getElementById('obj_' + i + '_conf').value;
    params['obj_' + i + '_quant'] = quantity;
    params['obj_' + i + '_path'] = path;
    params['obj_' + i + '_conf'] = conf;
  }
  $("#overlay_content").load(urlUpdateQuant, params,
     function(responseText, textStatus, XMLHttpRequest){
       $("#header_cart_span").load(urlRefreshCart, null,
         function(responseText, textStatus, XMLHttpRequest){
         }
         );
     }
  );
}

/**
 * Updates product quantity in the cart.
 */
function updateProductQuantity(urlUpdateCart, index) {
  var params = {};
  var quantity = document.getElementById('obj_' + index + '_quant').value;
  var oldQuantity = document.getElementById('obj_' + index + '_oldQuant').value;
  if(quantity != oldQuantity){
    var path = document.getElementById('obj_' + index + '_path').value;
    var conf = document.getElementById('obj_' + index + '_conf').value;
    params['obj_quant'] = quantity;
    params['obj_path'] = path;
    params['obj_conf'] = conf;
    $.post(urlUpdateCart, params, function(data, textStatus) {
      }
    )
  }
}

/**
* Starts the download of the file.
*/
function ajaxStartDownload(exportUrl) {
  var iframe = document.createElement("iframe");
  iframe.style.display="none";
  iframe.id="filedownload";
  iframe.src=exportUrl;
  document.body.appendChild(iframe);
}

 /**
* Starts a redirect from the cart: send product request/product comparison.
*/
 function ajaxRedirectFromCart(redirectUrl, displayPreloader) {
   if(displayPreloader){
     var overlayPreloader = document.getElementById("overlay_preloader_shopping_card");
     overlayPreloader.style.visibility = "visible";
   }
   $("#overlay_content").load(redirectUrl, null,
       function(responseText, textStatus, XMLHttpRequest){
         if(displayPreloader){
           var overlayPreloader = document.getElementById("overlay_preloader_shopping_card");
           overlayPreloader.style.visibility = "hidden";
         }
      }
   );
 }

/**
 * Used in external search to reload tabs with different pages.
 */
function ajaxLoadExternalSearch(searchUrl, componentId) {
    $("#"+componentId).load(searchUrl, null,
        function(responseText, textStatus, XMLHttpRequest){
            // alert("Loaded Tab Content!\nresponseText:\n"+ responseText +
            // "\ntextStatus:\n" + textStatus);
        }
    );
}

function ajaxLoginOverlayWithError(targetUrl, errorMessage) {
      $("#overlay_content").load(targetUrl, null,
                function(responseText, textStatus, XMLHttpRequest){
                  var overlayDiv = document.getElementById("overlay");
                  overlayDiv.style.visibility = "visible";
                  var searchFrameDiv = document.getElementById("overlay_content");
                  searchFrameDiv.style.visibility = "visible";
                  showLoginError(errorMessage);
                }
              );
}

function showLoginError(errorMessage) {

    var textDiv = document.createElement('div');
    textDiv.setAttribute('style', 'text-align:center');
    var messageSpan = document.createElement('span');
    messageSpan.setAttribute('class', 'errortext');
    var errorText = document.createTextNode(errorMessage);

    // append the elements
    var loginMessagesDiv = document.getElementById('login_messages');
    loginMessagesDiv.appendChild(textDiv);
    textDiv.appendChild(messageSpan);
    messageSpan.appendChild(errorText);
}

/**
 * Used to log user out of session.
 */
function logout(logoutUrl) {
	jQuery.get(logoutUrl);
    location.reload(true);
}

function updatePageTitle(objectName, config) {
    if (config != null && config.split(" ").join("") != "" && config != objectName) {
        document.title = objectName + " - " + config;
    } else {
        document.title = objectName;
    }
}

/**
 * Updates the cart action.
 */
function updateCartAction(selectedId) {
    var newType = document.getElementById(selectedId + "_type").value;
    var newUrl = document.getElementById(selectedId + "_url").value;

    var actionTypeElement = document.getElementById("cart_action_type");
    var actionUrlElement = document.getElementById("cart_action_url");
    if (actionTypeElement != null && actionUrlElement != null) {
        actionTypeElement.value = newType;
        actionUrlElement.value = newUrl;
    }
}

/**
 * Performs the action selected in the shopping cart combobox.
 */
function performCartAction() {
  var actionTypeElement = document.getElementById("cart_action_type");
  var actionUrlElement = document.getElementById("cart_action_url");
  if (actionTypeElement != null && actionUrlElement != null) {
    var actionType = "";
    var actionUrl = "";
    if (actionTypeElement.value != null) {
      actionType = actionTypeElement.value;
    }
    if (actionUrlElement.value != null) {
      actionUrl = actionUrlElement.value;
    }
    if (actionType == "redirect") {
      ajaxRedirectFromCart(actionUrl, true);
    } else if (actionType == "export") {
        ajaxStartDownload(actionUrl);
    } else if (actionType == "external" ) {
      var addUrlElement = document.getElementById("send_to_flyer_creator_add_url");
      var addUrl = "";
      if (addUrlElement != null) {
        addUrl = addUrlElement.value;
      }
      $.get(addUrl);
      var popup = window.open(actionUrl, "flyer_creator_popup", "width=755,height=745,scrollbars=1,menubar=0,left=240,top=100");
    }
  }
}

/**
	Navigates to the target url but first searches in the ajax loaded HTML
	for the current tab selection:"tab_number_ajax" and
	updates the target url with tabNumber info.

	Note, this only works when called with a perfectly formed Deeplink url in SEO form.
	e.g. http://localhost:8081/pb/link/24209-24228-24309-24310-24313-35138/en/conf/0-0
	Should be called only with url generaqted by <pb:seourl....
*/
function langSelect(targetUrl) {
    var tabNrInput = document.getElementById("tab_number_ajax");
    if (tabNrInput != null){
        var tabNrInputVal = tabNrInput.value;
        if(tabNrInputVal != null && tabNrInputVal.split(" ").join("") != "" ){
            var tabNr = tabNrInputVal;
			var lastIndexSlash = targetUrl.lastIndexOf("/");
		    var targetUrlBase = targetUrl.substring(0, lastIndexSlash);
	    	var url = targetUrlBase + "/" + tabNr + "-" + 0;
	    	document.location.href = url;
        } else{
        	document.location.href = targetUrl;
        }
    } else {
    	document.location.href = targetUrl;
    }
}

function showOtherCountryFieldInContactForm(selectElement) {
	var countryCode = $(selectElement).val();
	if(countryCode == "country.other") {
		$(".otherCountry").show();
	} else {
		$(".otherCountry").hide();
	}
}	

function showOtherCountryFieldInProductRequestForm(selectElement) {
	var countryCode = $(selectElement).val();
	if(countryCode == "country.other") {
		$(".otherCountry").show();
	} else {
		$(".otherCountry").hide();
	}
	$('#state-select option').hide();
	$("#first-option").show();
	$("#first-option").attr("selected", "true");
	switch(countryCode) {
		case "country.us":
			$("option[id^=state.us]").show();
			$(".stateRow").show();
		break;
		case "country.ar":
			$("option[id^=state.ar]").show();
			$(".stateRow").show();
		break;
		case "country.br":
			$("option[id^=state.br]").show();
			$(".stateRow").show();			
		break;
		case "country.ca":
			$("option[id^=state.ca]").show();
			$(".stateRow").show();
		break;
		case "country.cl":
			$("option[id^=state.cl]").show();
			$(".stateRow").show();
		break;
		case "country.mx":
			$("option[id^=state.mx]").show();
			$(".stateRow").show();
		break;
		case "country.ve":
			$("option[id^=state.ve]").show();
			$(".stateRow").show();
		break;
		default: $(".stateRow").hide();
	}
	
}

function setCookie (name, value, expires, path, domain, secure) 
{ 
	document.cookie = name + "=" + escape(value) + 
	((expires) ? "; expires=" + expires : "") + 
	((path) ? "; path=" + path : "") + 
	((domain) ? "; domain=" + domain : "") + 
	((secure) ? "; secure" : ""); 
} 


function setItemsCookie(value) {
	var now = new Date();
    var diff = 1000 * 60 * 60 * 24 * 365;
    var expires = new Date(now.getTime() + diff);
	setCookie("PBROWSER.ITEMS", value, expires.toGMTString(), "/"); 
}

function redirect(url)
{
    location.href = url;
}

function onReturnKey(event, url) {
    
	if (event.keyCode == 13) 
	{
	    redirect(url)
	}
	   
	}

	function redirect(url)
	{
	    location.href = url;
	}


