/*
 * Javascript functions to be used for the product page.
 * Uses /include/include.js, jQuery 1.2.6+
 */
if (typeof(jQuery)!="undefined") {
	var tse = {}; // create namespace
	// Use jQuery via $j(...)
	var $j = jQuery.noConflict();
	/* Start tell-a-friend (taf) class    
	*/
	tse.tellafriend = function(){
	    var me = {};
	    /* private array holding the IDs of different input fields. */
	    var textNames = new Array("tafYourNameText", "tafYourEmailText", "tafRecipientEmailText");
	    /* private variables that will be populated from the function populateVars */
	    var yourNameMsg;
	    var yourEmailMsg;    
	    var recipientEmailMsg;
	    var yourNameHelpMsg;
	    var emailHelpMsg;
	    
	    /**
	     * Method used to populate private variables. 
	     * Must be called before using this class.
	     * DTO must contain the following attributes:
	     * yourName
	     * yourEmail 
	     * recipientEmail 
	     * yourNameHelpMsg 
	     * emailHelpMsg                              
	     */         
	    me.populateVars = function(fieldNamesDTO) {  
	      yourNameMsg = fieldNamesDTO.yourName;
	      yourEmailMsg = fieldNamesDTO.yourEmail;
	      recipientEmailMsg = fieldNamesDTO.recipientEmail;
	      yourNameHelpMsg = fieldNamesDTO.yourNameHelpMsg;
	      emailHelpMsg = fieldNamesDTO.emailHelpMsg;
	    };
	    
	    /**
	     * Disable buttonsScrips.js when the TAF window is opened,
	     * otherwise it is impossible to make newlines in the message input area.
	     */
	    me.openTAFBox = function() {	   	    		    		    	
	    	document.onkeydown = null;
	    };
	    
	    /**
	     * Call this method to send an E-mail from 'yourEmail' to 'recipientEmail'.
	     * Method will gather form data, clear previous errors, validate data
	     * and finally make an AJAX call to server to send the e-mail or prompt
	     * the user to fix any errors found during validation.               
	     */         
	    me.sendEmail = function() {
	      /* gather data from page */      
	      var oid = $j("input[@name=OID]").val();                        
	      var yourName = jQuery.trim($j("#tafYourName").val());
	      var yourEmail = jQuery.trim($j("#tafYourEmail").val());
	      var recipientEmail = jQuery.trim($j("#tafRecipientEmail").val());
	      var msg = jQuery.trim($j("#tafMsg").val());
	      var noErrors = true;                    
	            
	      _clearErrors();
	      
	      /* Begin validation of input. */
	      if (yourName.length < 1) {
	        noErrors = false;
	        _markError(textNames[0], yourNameMsg, yourNameHelpMsg);      
	      }
	      yourName = _escapeTxt(yourName);
	      
	      msg = _fixMsg(msg);      
	      
	      /* regExp used to check if E-mail contains valid chars */
	      var emailCheckRegExp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	  
	      if (!emailCheckRegExp.test(yourEmail)) {      
	        noErrors = false;
	        _markError(textNames[1], yourEmailMsg, emailHelpMsg);      
	      }
	      
	      if (!emailCheckRegExp.test(recipientEmail)) {      
	        noErrors = false;
	        _markError(textNames[2], recipientEmailMsg, emailHelpMsg);
	      }
	      
	      if (noErrors) {        
	        $j("#tafMainBox").hide();
	        $j("#tafSendingBox").show();
	        /* Construct jaxletUrl and do JSON call */
	        var jaxletUrl = "/privat/produkter_tjanster/tellAFriend.jaxlet?oid=" + oid;
	        jaxletUrl += "&senderName=" + yourName + "&senderEmail=" + yourEmail;
	        jaxletUrl += "&recipientEmail=" + recipientEmail + "&message=" + msg;        
	        Tse.Ajax.doJsonCall(jaxletUrl, tse.tellafriend.callback, []);
	        
	      } else {
	        $j("#tafErrorBox").show();
	      }
	    };        
	    
	    /**
	     * This method is invoked when AJAX call is complete.
	     * It will display a message telling the user whether or not the mail was sent.     
	     */         
	    me.callback = function(jsonResponse) {
	      var message = jsonResponse["string"];
	      $j("#tafMainBox").hide();
	      $j("#tafSendingBox").hide();
	      $j("#tafSentMessage").html(message);
	      $j("#tafSentBox").show();
	    };    
	    
	    /**
	     * Call this method to reset the taf-box.
	     */             
	    me.resetTAFBox = function() {      
	      _clearErrors();
	      
	      // Enable buttonsScrips.js again when closing the TAF window
	      try {	    		
	    	document.onkeydown = nextEventTrigger;	    		    		    		
	      } catch(exception) {
	    	  // Some pages don't use buttonScrips.js, and that is OK
	      }
	      	      
	      $j("#tafSentBox").hide();
	      $j("#tafSendingBox").hide();
	      $j("#tafYourName").val("");
	      $j("#tafYourEmail").val("");
	      $j("#tafRecipientEmail").val("");
	      $j("#tafMsg").val("");
	      $j("#tafMainBox").show();	      
	    };
	    	    	    	    
	    /**
	     * Private method used to clear error message div as well as any error fields.    
	     */    
	    var _clearErrors = function() {
	      $j("#tafErrorBox").hide();
	      $j("#tafErrors").empty();
	      for (var i = 0; i<textNames.length;i++) {
	        var text = $j("#"+textNames[i]);
	        text.removeClass("errorfieldname");
	        if (text.html().indexOf("\u00BB") > -1) {
	          var t = text.html();
	          text.html(t.substr(1));
	        }
	      }
	    };
	    
	    /**
	     * Private method used to add an error message for a specific field.
	     * It will also mark the field with a different CSS class and a special tag.    
	     */         
	    var _markError = function(fieldTextId, fieldName, fieldHelp) {
	      var errorDiv = $j("#tafErrors").html();
	      errorDiv += "<span class=\"errorfieldname\">- " + fieldName + "</span> ";
	      errorDiv += "<span class=\"errorfieldhelp\">" + fieldHelp + "</span><br />";
	      $j("#tafErrors").html(errorDiv);
	      var ft = $j("#"+fieldTextId);
	      ft.addClass("errorfieldname");
	      if (ft.html().indexOf("\u00BB") < 0) {        
	        var t = ft.html();
	        ft.html("\u00BB" + t);
	      }
	    };
	    
	    /* Private method for removing <>-tags and their contents from uncleanText. 
	     * Cleaned data is returned.
	     * Example: <span>hello</span> will be returned as hello.     
	     */
	    var _removeHtmlTags = function(uncleanText) {        
	        /* This line is optional, it replaces escaped brackets with real ones, 
	      		i.e. < is replaced with < and > is replaced with > */	
	      	uncleanText = uncleanText.replace(/&(lt|gt);/g, function (strMatch, p1){
	      		return (p1 == "lt")? "<" : ">";
	      	});      	
	      	return uncleanText.replace(/<\/?[^>]+(>|$)/g, "");      		
	    };
	    
	    /**
	     * Private method, used to get a certain parameter from the URL.
	     */         
	    _getParameter = function (name){
	      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	      var regexS = "[\\?&]"+name+"=([^&#]*)";
	      var regex = new RegExp( regexS );
	      var results = regex.exec( window.location.href );
	      if( results == null )
	        return "";
	      else
	        return results[1];
	    };
	    
	    /**
	     * Method used to cap message length, remove htmlTags, fix special characters 
	     * and finally encodes the message.
	     * Returns the fixed 
	     */
	    _fixMsg = function(msg) {
	    	var fixedMsg = msg;
	    	fixedMsg = _removeHtmlTags(fixedMsg);
	    	/* Cap message to prevent too long input */
	        if (fixedMsg.length > 2000) {
	        	fixedMsg = fixedMsg.substr(0, 2000);
	        }
	        fixedMsg = _escapeTxt(fixedMsg);                
	        return fixedMsg;
	    };      
	       
	    /**
	     * Method used to convert all characters in a given string to escaped versions. 
	     */
	    _escapeTxt = function(inputString){
	      var ns='';
	      var t;
	      var chr='';
	      var cc='';
	      var tn='';
	      for(i=0;i<256;i++){
	        tn=i.toString(16);
	        if(tn.length<2)tn="0"+tn;
	        cc+=tn;
	        chr+=unescape('%'+tn);
	      }
	      cc=cc.toUpperCase();
	      inputString.replace(String.fromCharCode(13)+'',"%13");
	      for(q=0;q<inputString.length;q++){
	        t=inputString.substr(q,1);
	        for(i=0;i<chr.length;i++){
	          if(t==chr.substr(i,1)){
	            t=t.replace(chr.substr(i,1),"%"+cc.substr(i*2,2));
	            i=chr.length;
	          }
	        }
	        ns+=t;
	      }      
	      return ns;
	    };
	    
	    return me;
	  }();
	}
/* End tell-a-friend class */

/**
 * Validate the productForm berfore submit.
 */ 
function validateForm() {
	if(document.productForm.elements['quantities'] && (!document.productForm.quantities.value.match(/^[0-9]+$/) 
		|| document.productForm.quantities.value <= 0)) {
		document.productForm.quantities.focus();
		alert(document.productForm.invalidQuantityMsg.value);
		return; //Don't submit form
	} 
	if(document.productForm.elements['articleNumber'] && (document.productForm.articleNumber.value == "" 
		|| document.productForm.articleNumber.value == 0)) {
		document.productForm.articleNumber.focus();
		alert(document.productForm.invalidArticleNoMsg.value);
		return; //Don't submit form
		
	}
	// Submit form if we reach this point
	document.productForm.submit( );
}

/**
 * Update form action, target to match selected order flow.
 */ 
function updateFormAction(action,target) {
	document.productForm.action = action;
	document.productForm.target = target;
}

/**
 * Update admin button link to match selected admin flow.
 */ 
function updateAdminButtonLink(href,target) {
	getDOMObject('adminButton').href = href;
	getDOMObject('adminButton').target = target;
}

/**
 * Get OID and action URL from current selected item in drop down list
 * and set on the form.
 */
function setProductInfo() {

	 var currVal = document.productForm.productInfo.options[document.productForm.productInfo.selectedIndex].value;	 
	 var _idx1 = currVal.indexOf(";");
	 var _idx2 = currVal.lastIndexOf(";");
	 var _oid = "";
	 var _url = "";
	 var _target = "";
	
	 if(_idx1 > -1 && _idx2 > -1) {
	 		// get oid
		 	_oid = currVal.substring(0, _idx1);
		 	
		 	// get url
		 	if((_idx1+1) < _idx2) {
		 			_url = currVal.substring(_idx1+1, _idx2);					
			}
			
			// get target
			if(_idx2 < currVal.length) {
					_target = currVal.substring(_idx2+1, currVal.length);
			}
	 }
	 
	 if(_oid != "") {
			document.productForm.OID.value = _oid;
	 }
	 
	 if(_url != "") {
			document.productForm.action = _url;
	 }
	 
	 // always (re)set target
	 document.productForm.target = _target;
}

/**
 * Function for overriding the "Enter submits form"-problem
 * on the product page to call our own submit function.
 * USAGE:
 * <INPUT NAME="password" TYPE="PASSWORD" SIZE="10" onKeyPress="return submitEnterKey(event)">
 */
function submitEnterKey(keyEvent) {
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if (keyEvent)
		keycode = keyEvent.which;
	else
		return true;
	
	// call our submit function if ENTER-key is pressed
	if (keycode == 13) {
	   validateForm();
	   return false;
	}
	
	return true;
}
