/* 
 * Cross-browser event handling, by Scott Andrew
 */
function addEvent(element, eventType, lamdaFunction, useCapture) {
    if (element.addEventListener) {
        element.addEventListener(eventType, lamdaFunction, useCapture);
        return true;
    } else if (element.attachEvent) {
        var r = element.attachEvent('on' + eventType, lamdaFunction);
        return r;
    } else {
        return false;
    }
}

/* 
 * Kills an event's propagation and default action
 */
function knackerEvent(eventObject) {
    if (eventObject && eventObject.stopPropagation) {
        eventObject.stopPropagation();
    }
    if (window.event && window.event.cancelBubble ) {
        window.event.cancelBubble = true;
    }
    
    if (eventObject && eventObject.preventDefault) {
        eventObject.preventDefault();
    }
    if (window.event) {
        window.event.returnValue = false;
    }
}

/* 
 * Safari doesn't support canceling events in the standard way, so we must
 * hard-code a return of false for it to work.
 */
function cancelEventSafari() {
    return false;        
}

/* 
 * Cross-browser style extraction, from the JavaScript & DHTML Cookbook
 * <http://www.oreillynet.com/pub/a/javascript/excerpt/JSDHTMLCkbk_chap5/index5.html>
 */
function getElementStyle(elementID, CssStyleProperty) {
    var element = document.getElementById(elementID);
    if (element.currentStyle) {
        return element.currentStyle[toCamelCase(CssStyleProperty)];
    } else if (window.getComputedStyle) {
        var compStyle = window.getComputedStyle(element, '');
        return compStyle.getPropertyValue(CssStyleProperty);
    } else {
        return '';
    }
}

/* 
 * CamelCases CSS property names. Useful in conjunction with 'getElementStyle()'
 * From <http://dhtmlkitchen.com/learn/js/setstyle/index4.jsp>
 */
function toCamelCase(CssProperty) {
    var stringArray = CssProperty.toLowerCase().split('-');
    if (stringArray.length == 1) {
        return stringArray[0];
    }
    var ret = (CssProperty.indexOf("-") == 0)
              ? stringArray[0].charAt(0).toUpperCase() + stringArray[0].substring(1)
              : stringArray[0];
    for (var i = 1; i < stringArray.length; i++) {
        var s = stringArray[i];
        ret += s.charAt(0).toUpperCase() + s.substring(1);
    }
    return ret;
}

/*
 * Disables all 'test' links, that point to the href '#', by Ross Shannon
 */
function disableTestLinks() {
  var pageLinks = document.getElementsByTagName('a');
  for (var i=0; i<pageLinks.length; i++) {
    if (pageLinks[i].href.match(/[^#]#$/)) {
      addEvent(pageLinks[i], 'click', knackerEvent, false);
    }
  }
}

/* 
 * Cookie functions
 */
function createCookie(name, value, days) {
    var expires = '';
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        var expires = '; expires=' + date.toGMTString();
    }
    document.cookie = name + '=' + value + expires + '; path=/';
}

function readCookie(name) {
    var cookieCrumbs = document.cookie.split(';');
    var nameToFind = name + '=';
    for (var i = 0; i < cookieCrumbs.length; i++) {
        var crumb = cookieCrumbs[i];
        while (crumb.charAt(0) == ' ') {
            crumb = crumb.substring(1, crumb.length); /* delete spaces */
        }
        if (crumb.indexOf(nameToFind) == 0) {
            return crumb.substring(nameToFind.length, crumb.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, '', -1);
}

/*
 * Makes sure that the entered value is a number use via onKeyPress="checkNum()" on the textbox
 */ 
function checkNum(evt)
{       
    if(navigator.appName == 'Netscape')
    {
        // Bug ID: 2243, Fixed by: Ashish Sharma, Date: 01/08/2008        
        var carCode = evt.which;       
        if ((carCode < 48 || carCode > 57) && carCode != 8 && carCode != 16 && carCode != 0)
        {
            evt.preventDefault();
            evt.returnValue = false; 
        }     
    }
    else
    {
        var carCode = evt.keyCode;
        if ((carCode < 48) || (carCode > 57))
        {           
            evt.cancelBubble = true	
            evt.returnValue = false;	
        }
    }
}
// Bug ID: 2243, Fixed by: Ashish Sharma, Date: 01/08/2008
// Checks the validity of data to be copied. If data is not valid old data remains in the text box.
function doBeforePaste(evt)
{
    var textBox = null;
    if(navigator.appName == 'Netscape')
    {
        textBox = evt.target.id;
    }
    else
    {
        textBox = evt.srcElement.id;
    }
    var sData = window.clipboardData.getData("Text");         
    var isValid = 1;
    if(sData != null)
    {
        for(var i=0; i<=sData.length; ++i)
        {
              var carCode = sData.charCodeAt(i);
              if(carCode < 48 || carCode > 57)
              {
                    isValid = 0;
                    break;
              }
         }
         if(isValid == 1)
         { 
            window.clipboardData.setData("Text", sData);
         }
         else
         {
           window.clipboardData.setData("Text", document.getElementById(textBox).value);
         }
     }
}

// Bug ID: 2243, Fixed by: Ashish Sharma, Date: 01/08/2008
// Cancel default behavior and create a new paste routine
function doPaste(evt)
{
    var textBox = null;
    if(navigator.appName == 'Netscape')
    {
        textBox = evt.target.id;
    }
    else
    {
        textBox = evt.srcElement.id;
    }
    textBox.value = window.clipboardData.getData("Text");           
}

   function TakeConfirmation(sender, name)
    {
        var retVal = false;
        if(sender.innerText == 'Activate')
        {
            retVal = confirm('Are you sure you want to activate ' + name + '?');
        }
        else
        {
            retVal = confirm('Are you sure you want to inactivate ' + name + '?');
        }
        return retVal;
    }

/*
 * Disable Enter key on page.
 */ 
function disableEnterKey(evt)
{
    if(navigator.appName == 'Netscape')
    {
        if (evt.which == 13)
        {
            evt.preventDefault();
            evt.returnValue = false; 
        }       
    }
    else
    {
        if (evt.keyCode == 13) 
        {
            evt.returnValue = false; 
            evt.cancel = true;
        }
    }
}

/*
 * Function to validate the Message length in page, it should not be more than 200 chars
 */ 
function validateMessageLength(source, arguments)
{
    var num = 0;
    num = arguments.Value.length;
    //alert(num);
    if (num > 200)
    {
        arguments.IsValid=false;
        return false;
    }
    else
    {
        arguments.IsValid=true;
        return true;
    } 
}

// Method to Pad a string from Left
function padleft(val, ch, num) {
    var re = new RegExp(".{" + num + "}$");
    var pad = "";

    do  {
        pad += ch;
    }while(pad.length < num)

    return re.exec(pad + val);
}
// Method to Pad a string from Right
function padright(val, ch, num){
    var re = new RegExp("^.{" + num + "}");
    var pad = "";

    do {
        pad += ch;
    } while (pad.length < num)

    return re.exec(val + pad);
}

// Bug Id: 1483, Fixed By: Pranay Arora, Date: 11/01/2007
// Removed confirmMessage() method
/*  
    Method redirects the user to the specified url, if affirmative, after showing a confirmation message for data loss, 
    else it remains on the same page.
*/
function confirmCancelAndRedirect(url)
{        
		var response = confirm('Are you sure you wish to cancel? Any changes you have made will be lost.');
		
		if(url != '')
		{
		    if (response)
		    {
		        window.location.href = url;
		        return false;
		    }
		    else
		    {
		        return false;
		    }
		}
		else
		{
            if (response)
            {
                return true;
            }
            else
            {
                return false;           
            }
        }
}

function confirmCancelAndRedirectForAccountProduction(url)
{        
		var response = confirm('Are you sure you wish to cancel? Any changes you have made will be lost.');
		
		if(url != '')
		{
		    if (response)
		    {
		        window.location.href = url;
		        return false;
		    }
		    else
		    {
		        return false;
		    }
		}
		else
		{
            if (response)
            {
                return true;
            }
            else
            {
                return false;           
            }
        }
}


// Method redirects the user to the specified url after showing a confirmation message
function confirmSaveAndRedirect(url)
{
    alert('Your information has been saved.');
    
    if (url != '')
    {
        window.location.href = url;
    }
}

// Method to redirect the user the specified url
function redirectToUrl(url)
{
    if (url != '')
    {
        window.location.href = url;
    }
}

// The page displayed in iframe and the iframe should be in same domain.
// This script is putting both of them into a same domain(Cargill.com/CargillAg.com).
function setDomainName()
{
    var host = document.location.host       
    var hostArray = host.split(".");
    var domainLength = hostArray.length;    
    var domainName = "localhost";          // This is used for the development boxes.
    var hostArrayLength = hostArray.length;
    
    // Set the domain name to cargill.com or cargillAg.com.
    if(hostArray.length > 1)
    {
        domainName = hostArray[domainLength - 2] + "." + hostArray[domainLength - 1];  // It can have values "Cargill.com"/"CargillAg.com".
    }
    
    // Set the document domain to the domainName
    document.domain = domainName;
}

// Bug Id: 1564, Fixed By: Pranay Arora, Date: 11/07/2007
/*
Function to read the cookie value.
*/
function ReadCookie(cookieName) 
{
    var theCookie = "" + document.cookie;
    var ind = theCookie.indexOf(cookieName);
    
    if (ind == -1 || cookieName == "") 
    {
        return "";
    }
    
    var ind1 = theCookie.indexOf(';', ind);
    
    if (ind1==-1)
    {
        ind1 = theCookie.length;
    }
    
    return theCookie.substring(ind + cookieName.length + 1, ind1)   ;
}

// Bug Id: 1564, Fixed By: Pranay Arora, Date: 11/07/2007
/*
Pre-Loads the zipcode.
*/
function PreLoadZipCode()
{
    var zipcodeValue = ReadCookie("ZipCode");
    var zipcodeTextbox = document.getElementById("zipcode");
    
    if (zipcodeTextbox != null)
    {
        zipcodeTextbox.value = zipcodeValue;
    }
}

// Bug Id: 1564, Fixed By: Sunil Ghanta, Date: 02/08/2008
/*
Pre-Loads the ContactUs.
*/

function PreLoadContactUs(fNameValue, lNameValue, eMailValue, zipcodeValue)
{
    var fNameTextbox = document.getElementById("fname");
    var lNameTextbox = document.getElementById("lname");
    var eMailTextbox = document.getElementById("email");
    var zipcodeTextbox = document.getElementById("zipcode");
    
    if (fNameTextbox != null) 
        fNameTextbox.value = fNameValue;
        
    if (lNameTextbox != null) 
        lNameTextbox.value = lNameValue;
        
    if (eMailTextbox != null)
        eMailTextbox.value = eMailValue; 
    
    if (zipcodeTextbox != null)
        zipcodeTextbox.value = zipcodeValue;
}

//qualify an HREF to form a complete URI   
function qualifyHREF(href)   
{   
    //get the current document location object   
    var loc = document.location;   
  
    //build a base URI from the protocol plus host (which includes port if applicable)   
    var uri = loc.protocol + '//' + loc.host;   
  
     //if the input path is relative-from-here   
     //just delete the ./ token to make it relative   
     if(/^(\.\/)([^\/]?)/.test(href))   
     {   
         href = href.replace(/^(\.\/)([^\/]?)/, '$2');   
     }   
   
     //if the input href is already qualified, copy it unchanged   
     if(/^([a-z]+)\:\/\//.test(href))   
     {   
         uri = href;   
     }   
   
     //or if the input href begins with a leading slash, then it's base relative   
     //so just add the input href to the base URI   
     else if(href.substr(0, 1) == '/')   
     {   
         uri += href;   
     }   
   
     //or if it's an up-reference we need to compute the path   
     else if(/^((\.\.\/)+)([^\/].*$)/.test(href))   
     {   
         //get the last part of the path, minus up-references   
         var lastpath = href.match(/^((\.\.\/)+)([^\/].*$)/);   
         lastpath = lastpath[lastpath.length - 1];   
   
         //count the number of up-references   
         var references = href.split('../').length - 1;   
   
         //get the path parts and delete the last one (this page or directory)   
         var parts = loc.pathname.split('/');   
         parts = parts.splice(0, parts.length - 1);   
   
         //for each of the up-references, delete the last part of the path   
         for(var i=0; i<references; i++)   
         {   
             parts = parts.splice(0, parts.length - 1);   
         }   
   
         //now rebuild the path   
         var path = '';   
         for(i=0; i<parts.length; i++)   
         {   
             if(parts[i] != '')   
             {   
                 path += '/' + parts[i];   
             }   
         }   
         path += '/';   
   
         //and add the last part of the path   
         path += lastpath;   
   
         //then add the path and input href to the base URI   
         uri += path;   
     }   
   
     //otherwise it's a relative path,   
     else   
     {   
         //calculate the path to this directory   
         path = '';   
         parts = loc.pathname.split('/');   
         parts = parts.splice(0, parts.length - 1);   
         for(var i=0; i<parts.length; i++)   
         {   
             if(parts[i] != '')   
             {   
                 path += '/' + parts[i];   
             }   
         }   
         path += '/';   
   
         //then add the path and input href to the base URI   
         uri += path + href;   
     }   
   
     //return the final uri   
     return uri;   
 }  
 
 //It sets the hidden field on changing the Role in contact detail page
 function SetHiddenField(DropdownObject, HiddenObject)
 {
    HiddenObject.value = DropdownObject.value;
 }

/*
 * Function to validate the Message length in page, it should not be more than 200 chars
 */ 
function checkDSIdLength(source, arguments)
{
    var num = 0;
    num = arguments.Value.length; 
    var reg = new RegExp("^[a-zA-Z0-9]*$")
    var isValid;
    //Bug ID 2362, solved by Sandeep Mittal by removing = from the operator >=
        if (num < 2 || num>20)
        {
            isValid =false;
            arguments.IsValid=isValid; 
            return false;
        }
        else
        {
           isValid=true;
        }
    
        //check for alphanumeric
         if(reg.test(arguments.Value))
         {
            arguments.IsValid =true;
            return true;
         }
         else
         {
             arguments.IsValid=false 
             return false;
         }
         
     
     }
//Bug ID 2367 solved by Sandeep  Mittal on 8 Jan 2008 by Adding confirmCancelAndRedirectForEmployeeDetail functinality.
function confirmCancelAndRedirectForEmployeeDetail(url)
{        
		var response = confirm('Are you sure you wish to cancel? Any changes you have made will be lost.');
		
		if(url != '')
		{
		    if (response)
		    {
		        window.location.href = url;
		        return false;
		    }
		    else
		    {
		        return false;
		    }
		}
		else
		{
            if (response)
            {
                return true;
            }
            else
            {
                return false;           
            }
        }
}
//Bug ID 2363 solved by Sandeep  Mittal on 8 Jan 2008 by Adding confirmDeleteAndRedirectForEmployeeDetail functinality.
function confirmDeleteAndRedirectForEmployeeDetail()
{        
		var response = confirm('Are you sure you wish to delete association?');
		
            if (response)
            {
                return true;
            }
            else
            {
                return false;           
            }
}

/*
 * Function to validate argument is a valid whole number 
 */ 
function checkNumeric(source, arguments)
{
    var num = 0;
    num = arguments.Value.length; 
    var reg = new RegExp("^[0-9]*$")
    var isValid;
    
        //check for numeric
         if(reg.test(arguments.Value))
         {
            arguments.IsValid =true;
            return true;
         }
         else
         {
             arguments.IsValid=false 
             return false;
         }
         
     
     }

/*
 * Function to validate argument is a valid whole number 
 */
  
    function openNewBrowser(url, title)
    {
        window.open(url, title);
        return false;
    }
    
    
    /*
     * check for valid page number 
     */
    function checkPageNumber(txtBox,pageCount)
    {
        //fetch vlaue of a textbox
       var txtvalue=document.getElementById(txtBox).value
       
       var isNumeric= txtvalue;
       var reg = new RegExp("^[0-9]*$");
     //check if Page no is a whole number and not anything else  
    
        //check for numeric
         if(reg.test(isNumeric))
         {  
              isNumeric = parseInt(isNumeric);
              pageCount = parseInt(pageCount);
              //check if requested page no exists   
               if(isNumeric>0 && isNumeric<=pageCount)
               {
                   return true;
               }
               else
               {
                    alert("Page Number does not Exists.");
                    return false;
               }
         }         
         else
         {
            alert("Page Number should be Numeric.");
            return false;
         }
       
       }

//This Function fires an Confirm message on DropDown value change and check if user says Yes then PostBack 
//else return back and change the dropDown value back to original
//Used in Account\AccountProduction.aspx.cs
function DropDownChangeIndex(eventTarget, eventArgument,listItem)
{
var retVal = false;
//Fix BUG 3190 for Change in message.
//By Sandeep Mittal on 2 Apr 2008.
var retVal =confirm('Any unsaved changes will be lost upon selecting a different commodity. Do you wish to continue?');
if(retVal)
{
    __doPostBack(eventTarget,eventArgument);
}
else
{
 // Get a reference to the drop-down
    var myDropdownList = document.getElementById(eventTarget);
    
    // Loop through all the items
    for (iLoop = 0; iLoop< myDropdownList.options.length; iLoop++)
    {    
      if (myDropdownList.options[iLoop].value == listItem)
      {
        // Item is found. Set its selected property, and exit the loop
        myDropdownList.options[iLoop].selected = true;
        break;
      }
    }
}

return retVal ;
} 

function AlertMessage(msg)
{
    alert(msg);
}

function EndRequestHandler(sender, args) 
{
    if (args.get_error() != undefined)
           {
               // If we don't get a response from the server, assume they have been logged out and redirect to the Summary page.
        alert("Your session has expired.");
        window.location = '/Account/AccountSummary.aspx';
               args.set_errorHandled(true);
           }
}

function loadErrorHandler() 
{
    // We sometimes get "Sys is undefined" errors.  Catch and ignore the error.
    try
       {
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
       }
	catch (error)
       {
	    //ignore the error
       }
}
