
/*
Initialize SKYSALES namespace
All javascript in skysales should be behind the SKYSALES namespace
This prevents naming collisions
*/

/*global window: false, SKYSALES: true, $: false, document: false, alert: false */
/* BDW 3/11: per INC 172829 , commenting out use strict because it breaks FF 4 */

//'use strict';

SKYSALES = {};

/*
Name: 
Class Common
Param:
None
Return: 
An instance of Common
Functionality:
Provide common functionality and events on every view.
Notes:
This should be put in the SKYSALES.Class namespace.
Class Hierarchy:
Common
*/
SKYSALES.Common = {};

SKYSALES.Common.IsEmpty = function (element) 
{
    var val = null;
    var retVal = false;
    var defaultValue = '';
    if ((element) && (defaultValue === undefined)) {
        if (element.requiredempty) {
            defaultValue = element.requiredempty;
        }
        else {
            defaultValue = '';
        }
    }

    val = SKYSALES.Common.getValue(element);
    if ((val === null) || (val === undefined) || (val.length === 0) || (val === defaultValue)) {
        retVal = true;
    }
    return retVal;
};

//Adds an event to the dom, and sets a function handler
SKYSALES.Common.addEvent = function (obj, eventString, functionRef) 
{
    $(obj).bind(eventString, functionRef);
};

//Returns the value of an html form element
SKYSALES.Common.getValue = function (e) 
{
    var val = null;
    if (e) 
    {
        val = $(e).val();
        return val;
    }
    return null;
};


//Collapsing panel js
 function ToggleCollapseState(collapseButton, bodyDiv)
{
    try
    {
      var bodyDivRef = document.getElementById(bodyDiv);

      if (bodyDivRef)
      {
        if (bodyDivRef.style.display == 'none' || bodyDivRef.className.indexOf('hidden') > -1)
        {
          collapseButton.src = 'images/Base/button-collapse.gif';
          if (collapseButtonHideTitle)
          {
            collapseButton.title = 'Hide';
          }
          bodyDivRef.style.display = 'block';
          
          if (bodyDivRef.className.indexOf('hidden') > -1)
          {
            bodyDivRef.className = bodyDivRef.className.substring(0, bodyDivRef.className.indexOf('hidden') -1); 
          }
        }
        else
        {
         collapseButton.src = 'images/Base/button-expand.gif';
          if (collapseButtonShowTitle)
          {
            collapseButton.title = collapseButtonShowTitle;
          }
          bodyDivRef.style.display = 'none';
        }
      }
      else
      {
        alert('Unable to find target body');
      }
    }
    catch (e)
    {
      alert(e.message);
    }
}

//Hints javascript
var defaultXOffset	= 0;
var defaultYOffset	= 0;
var hintDiv	= "cssHint"
function showHint(obj)
{
	showHint(obj,null,null, null);
}
function showHint(obj, xOffset, yOffset)
{
    showHint(obj, xOffset, yOffset, null)
}
function showHintWithReference(obj, referenceObject)
{
    showHint(obj, null, null, referenceObject)
}
function showHint(obj, xOffset, yOffset, referenceObject)
{
    var x = 0;
    var y = 0;
     
    if (!referenceObject)
    {
	    x 							= getX(obj);
	    y 							= getY(obj);
	    
	    if (xOffset == null)
	    {
    		x += obj.offsetWidth + 5;
	    }
	}
	else
	{
	    x = getX(referenceObject);
	    y = getY(referenceObject);
	    
	    if (xOffset == null)
	    {
    		x += referenceObject.offsetWidth + 5;
	    }
	}
	
	var hintHtml = '';
	
	//Get culture XML hint
	if (obj.getAttribute('hint') != null)
		hintHtml += obj.getAttribute('hint');
	
	//Get server hint
	if (obj.getAttribute('serverHint') != null)
	{
		if (obj.getAttribute('hintPriority') != null)
		{
			if (obj.hintPriority == 'server')
			{
				hintHtml = obj.getAttribute('serverHint') + hintHtml; 
			}
			else
			{
				hintHtml += obj.getAttribute('serverHint');
			}
		}
		else
		{
			hintHtml += obj.getAttribute('serverHint');
		}
	}
	getObject(hintDiv).innerHTML = hintHtml;
	getStyle(hintDiv).visibility 	= 'visible';
	xOffset	= (xOffset != null) ? xOffset : defaultXOffset;
	yOffset	= (yOffset != null) ? yOffset : defaultYOffset;
	getStyle(hintDiv).left 			= xOffset + x + 'px';
	getStyle(hintDiv).top 			= yOffset + y + 'px';
	//getStyle(hintDiv).height = 50;
	
}

function hideHint(obj)
{
	getStyle(hintDiv).visibility 	= 'hidden';
}

function getX(obj)
{
	var pos = 0;
	if (obj.x)	// N4
	{
		pos += obj.x;
	}
	else if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
		    pos += obj.offsetLeft;
			obj	 = obj.offsetParent;
		}
	}
	return pos;
}

function getY(obj)
{
    var count = 0;
	var pos = 0;
	if (obj.y) // netscape 4
		pos += obj.y;
	else if (obj)
	{
	     while(obj){		
	     pos+=obj.offsetTop;
		 obj=obj.offsetParent;
 	    }
	}
	return pos;
}

function getObject(name)
{
	if (document.getElementById) return document.getElementById(name);
	if (document.all) return document.all[name];
	if (document.layers)
	{
		if (document.layers[name]) return document.layers[name];
		else return document.layers[name].layers[name];
	}
}

function getStyle(name)
{
	if (document.getElementById) return document.getElementById(name).style;
	if (document.all) return document.all[name].style;
	if (document.layers)
	{
		if (document.layers[name]) return document.layers[name];
		else return	this.style = document.layers[name].layers[name];
	}
}

//End of hints



var events = new Array();

function register(eventName, functionName)
{
    
    if (eval(events[eventName]) == null)
	{
		events[eventName] = new Array();
	}
	events[eventName][events[eventName].length]	= functionName;
}

function raise(eventName, eventArgs)
{
	var undefined;

	if (events[eventName] != undefined)
	{
		for (var ix=0; ix<events[eventName].length; ix++)
		{
			if ( eval(events[eventName][ix] + "(eventArgs)") == false)
			{
				return false;
			}
		}
	}
	
	return true;
}

function WindowLoadEventArgs()
{
}

function WindowInitialize()
{
    var originalOnLoad = window.onload;
        
    window.onload = function()
        {
            raise('WindowLoad', new WindowLoadEventArgs());
   
            if (originalOnLoad)
            {
                originalOnLoad();
            }
        }
}

function debug()
{
    var items = debug.arguments.length;
    if (items > 0)
    {
        var strbuf = '' + debug.arguments[0] + ' [';
        
        for (var i=1; i < items; i++)
        {
            strbuf += '' + debug.arguments[i];
            if (items != (i + 1))
            {
              strbuf += ', ';
            }
        }
        alert(strbuf + ']');
    }
}

function displayPopUpConverter()
{
    var url = 'CurrencyConverter.aspx';

    if (!window.converterWindow || converterWindow.closed)
    {
      converterWindow = window.open(url,'converter','width=360,height=190,toolbar=0,status=0,location=0,menubar=0,scrollbars=0,resizable=0');
    }
    else
    {
      converterWindow.open(url,'converter','width=360,height=190,toolbar=0,status=0,location=0,menubar=0,scrollbars=0,resizable=0');
      converterWindow.focus();
    }
 }

var errorsHeader = 'Please correct the following.\n\n';

// <validation_javascript>

var errorsHeader = 'Please correct the following.\n\n';

function Validate(form, controlID, errorsHeader)
{
	// set up properties
	this.form = form;
	this.namespace = controlID;
	this.errors = '';
	this.setfocus = null;
	this.errorsHeader = errorsHeader;
	
	// set up attributes
	this.requiredAttribute = 'required';
	this.requiredEmptyAttribute = 'requiredEmpty';
	this.validationTypeAttribute = 'validationtype';
	this.regexAttribute = 'regex';
	this.minLengthAttribute = 'minlength';
	this.numericMinLengthAttribute = 'numericminlength';
	this.maxLengthAttribute = 'maxlength';
	this.numericMaxLengthAttribute = 'numericmaxlength';
	this.minValueAttribute = 'minvalue';
	this.maxValueAttribute = 'maxvalue';
	this.equalsAttribute = 'equals';
	
	// set up error handling attributes
	this.defaultErrorAttribute = 'error';
	this.requiredErrorAttribute = 'requirederror';
	this.validationTypeErrorAttribute = 'validationtypeerror';
	this.regexErrorAttribute = 'regexerror';
	this.minLengthErrorAttribute = 'minlengtherror';
	this.maxLengthErrorAttribute = 'maxlengtherror';
	this.minValueErrorAttribute = 'minvalueerror';
	this.maxValueErrorAttribute = 'maxvalueerror';
	this.equalsErrorAttribute = 'equalserror';
	
	// set up error handling default errors
	this.defaultError = '{fieldname} is invalid.'
	this.defaultRequiredError = '{fieldname} is required.';
	this.defaultValidationTypeError = '{fieldname} is invalid.';
	this.defaultRegexError = '{fieldname} is invalid.';
	this.defaultMinLengthError = '{fieldname} is too short in length.';
	this.defaultMaxLengthError = '{fieldname} is too long in length.';
	this.defaultMinValueError = '{fieldname} must be greater than {minValue}.';
	this.defaultMaxValueError = '{fieldname} must be less than {maxValue}.';
	this.defaultEqualsError = '{fieldname} is not equal to {equals}';
	this.defaultNotEqualsError = '{fieldname} cannot equal {equals}';
	
	// add methods to object
	this.run = run;
	this.validateSingleElement = validateSingleElement;
	this.outputErrors = outputErrors;
	this.checkFocus = checkFocus;
	this.setError = setError;
	this.cleanAttributeForErrorDisplay = cleanAttributeForErrorDisplay;
	this.validateRequired = validateRequired;
	this.validateType = validateType;
	this.validateRegex = validateRegex;
	this.validateMinLength = validateMinLength;
	this.validateMaxLength = validateMaxLength;
	this.validateMinValue = validateMinValue;
	this.validateMaxValue = validateMaxValue;
	this.validateEquals = validateEquals;
	
	// add validation type methods
	this.setValidateTypeError = setValidateTypeError;
	this.validateAmount = validateAmount;
	this.validateDate = validateDate;
	this.validateMod10 = validateMod10;
	this.validateNumeric = validateNumeric;
	
	//this.nonePattern = '^\.*$';
	this.stringPattern = '^.+$';	
	this.upperCaseStringPattern = '^[A-Z]([A-Z)|\s)*$';
	this.numericPattern = '^\\d+$';
	this.numericStripper = /\D/g;
	this.alphaNumericPattern = '^\\w+$';
	
	var amountSeparators = '(\\.|,)';
	this.amountPattern = '^(\\d+(' + amountSeparators + '\\d+)*)$';
	
	this.dateYearPattern = '^\\d{4}$';
	this.dateMonthPattern = '^\\d{2}$';
	this.dateDayPattern = '^\\d{2}$';
	
	var validEmailChars = '[^\:\,\;\#$\%\&\(\)\+\=\/]+';
	this.emailPattern = '^' + validEmailChars + '(\\.' + validEmailChars + ')?@' + validEmailChars + '(\\.' + validEmailChars + ')+$';
}

function run()
{
	// run validation on the form elements
	for (var i = 0; i < this.form.length; i++)
	{
		var e = this.form.elements[i];
		
		if (e.id.indexOf(this.namespace) == 0)
		{
			this.validateSingleElement(e);
		}
	}
	
	return this.outputErrors();
}

function outputErrors()
{
	// if there is an error output it
	if(this.errors)
	{
		alert(this.errorsHeader + this.errors);
		
		if (this.setfocus)
		{
			this.setfocus.focus();
		}
		
		return false;
	}
	
	return true;
}

function validateSingleElement(e)
{
	this.validateRequired(e);
	// only validate the rest if they actually have something
	if (0 < e.value.length)
	{
		this.validateType(e);
		this.validateRegex(e);
		this.validateMinLength(e);
		this.validateMaxLength(e);
		this.validateMinValue(e);
		this.validateMaxValue(e);
		this.validateEquals(e);
	}
}

function checkFocus(e)
{
	if (!this.setfocus)
	{
		this.setfocus = e;
	}
}

function validateRequired(e)
{
	var trimmed = e.value.replace(/^\s+|\s+$/g, '');
	if((e.getAttribute(this.requiredAttribute) == 'true') && ((trimmed.length < 1) || (e.value == e.getAttribute(this.requiredEmptyAttribute))))
	{
		this.setError(e, this.requiredErrorAttribute, this.defaultRequiredError);
	}
}

function validateType(e)
{
	var type = e.getAttribute(this.validationTypeAttribute);
	var value = e.value;
	
	if (type) 
	{
		if ((type == 'Address') && (!value.match(this.stringPattern)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'AlphaNumeric') && (!value.match(this.alphaNumericPattern)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'Amount') && (!this.validateAmount(value)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'Country') && (!value.match(this.stringPattern)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'Email') && (!value.match(this.emailPattern)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'Mod10') && (!this.validateMod10(value)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'Name') && (!value.match(this.stringPattern)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'Numeric') && (!this.validateNumeric(value)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type.indexOf('Date') == 0) && (!this.validateDate(e, type, value)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'State') && (!value.match(this.stringPattern)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'String') && (!value.match(this.stringPattern)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'UpperCaseString') && (!value.match(this.upperCaseStringPattern)))
		{
			this.setValidateTypeError(e);
		}
		else if ((type == 'Zip') && (!value.match(this.stringPattern)))
		{
			this.setValidateTypeError(e);
		}
		
	}
}

function validateRegex(e)
{
	var regex = e.getAttribute(this.regexAttribute);
	
	if ((regex) && (!e.value.match(regex)))
	{
		this.setError(e, this.regexErrorAttribute, this.defaultRegexError);
	}
}

function validateMinLength(e)
{
	var length = e.getAttribute(this.minLengthAttribute);
	var numericLength = e.getAttribute(this.numericMinLengthAttribute);
	
	if ((0 < length) && (e.value.length < length))
	{
		this.setError(e, this.minLengthErrorAttribute, this.defaultMinLengthError);
	}
	else if ((0 < numericLength)  && (0 < e.value.length) && (e.value.replace(this.numericStripper, '').length < numericLength))
	{
		this.setError(e, this.minLengthErrorAttribute, this.defaultMinLengthError);
	}
}

function validateMaxLength(e)
{
	var length = e.getAttribute(this.maxLengthAttribute);
	var numericLength = e.getAttribute(this.numericMaxLengthAttribute);
				
	if ((0 < length) && (length < e.value.length))
	{
		this.setError(e, this.maxLengthErrorAttribute, this.defaultMaxLengthError);
	}
	else if ((0 < numericLength)  && (0 < e.value.length) && (numericLength < e.value.replace(this.numericStripper, '').length))
	{
		this.setError(e, this.maxLengthErrorAttribute, this.defaultMaxLengthError);
	} 
}

function validateMinValue(e)
{
	var min = e.getAttribute(this.minValueAttribute);
	
	if ((min != null) && (0 < min.length))
	{
		if ((5 < min.length) && (min.substring(0, 5) == '&gt;='))
		{
			if (e.value < parseFloat(min.substring(5, min.length)))
			{
				this.setError(e, this.minValueErrorAttribute, this.defaultMinValueError);
			}
		}
		else if ((4 < min.length) && (min.substring(0, 4) == '&gt;'))
		{
			if (e.value <= parseFloat(min.substring(4, min.length)))
			{
				this.setError(e, this.minValueErrorAttribute, this.defaultMinValueError);
			}
		}
		else if (e.value < parseFloat(min))
		{
			this.setError(e, this.minValueErrorAttribute, this.defaultMinValueError);
		}
	}
}

function validateMaxValue(e)
{
	var max = e.getAttribute(this.maxValueAttribute);
	
	if ((max != null) && (0 < max.length))
	{
		if ((5 < max.length) && (max.substring(0, 5) == '&lt;='))
		{
			if (e.value > parseFloat(max.substring(5, max.length)))
			{
				this.setError(e, this.maxValueErrorAttribute, this.defaultMaxValueError);
			}
		}
		else if ((4 < max.length) && (max.substring(0, 4) == '&lt;'))
		{
			if (e.value >= parseFloat(max.substring(4, max.length)))
			{
				this.setError(e, this.maxValueErrorAttribute, this.defaultMaxValueError);
			}
		}
		else if (parseFloat(e.value) > max)
		{
			this.setError(e, this.maxValueErrorAttribute, this.defaultMaxValueError);
		}
	}
}

function validateEquals(e)
{
	// eventually this should be equipped to do string
	// comparison as well as other element comparisons
	
	var equal = e.getAttribute(this.equalsAttribute);
	
	if ((equal != null) && (0 < equal.length))
	{
		if ((2 < equal.length) && (equal.substring(0, 2) == '!='))
		{
			if (e.value == equal.substring(2, equal.length))
			{
				this.setError(e, this.equalsErrorAttribute, this.defaultEqualsError);
			}
		}
		else if ((2 < equal.length) && (equal.substring(0, 2) == '=='))
		{
			if (e.value != equal.substring(2, equal.length))
			{
				this.setError(e, this.equalsErrorAttribute, this.defaultEqualsError);
			}
		}
		else if (equal.charAt(0) == '=')
		{
			if (e.value != equal.substring(1, equal.length))
			{
				this.setError(e, this.equalsErrorAttribute, this.defaultEqualsError);
			}
		}
		else if (e.value != equal)
		{
			this.setError(e, this.equalsErrorAttribute, this.defaultEqualsError);
		}
	}
}

function setValidateTypeError(e)
{
	this.setError(e, this.validationTypeErrorAttribute, this.defaultValidationTypeError);
}

function setError(e, errorAttribute, defaultTypeError)
{
	var error = e.getAttribute(errorAttribute);
	if (!error)
	{
		if (e.getAttribute(this.defaultErrorAttribute))
		{
			error = e.getAttribute(this.defaultErrorAttribute);
		}
		else if (defaultTypeError)
		{
			error = defaultTypeError;
		}
		else
		{
			error = this.defaultError;
		}
	}
	
	// this would make more sense but it doesn't work
	// so i'll do each explicitly while i make this work
	var results = error.match(/{\s*(\w+)\s*}/g);
	if (results)
	{
		for (var i = 0; i < results.length; i++)
		{
			var dollarOne = results[i].replace(/{\s*(\w+)\s*}/, '$1');
			var replacement = this.cleanAttributeForErrorDisplay(e, dollarOne);
			if (replacement == 'fieldname')
				replacement = this.cleanAttributeForErrorDisplay(e, 'name');
				
			error = error.replace(/{\s*\w+\s*}/, replacement);
		}
	}
	
	this.errors += error + '\n';
	this.checkFocus(e);	
}

function cleanAttributeForErrorDisplay(e, attributeName)
{
	var attribute = e.getAttribute(attributeName.toLowerCase());
	
	if (attribute == null)
	{
		return attributeName;
	}
	
	if (attributeName.match(/^(minvalue|maxvalue)$/i))
	{
		return attribute.replace(/[^\d.,]/g, '');
	}
	
	return attribute;
}

function validateAmount(amount)
{
	if ((!amount.match(this.amountPattern)) || (amount == 0))
	{
		return false;
	}
	
	return true;
}

function validateDate(e, type, value)
{
	var today = new Date();
	
	if ((type == 'DateYear') && ((value < today.getYear()) || (!value.match(this.dateYearPattern))))
	{
		return false;
	}
	//just make sure it is two digits for now
	else if ((type == 'DateMonth') && (!value.match(this.dateMonthPattern)))
	{
		return false;
	}
	//just make sure it is two digits for now
	else if ((type == 'DateDay') && (!value.match(this.DateDayPattern)))
	{
		return false;
	}
	
	return true;
}

function validateMod10(cardNumber)
{
	var isValid = false;
	var ccCheckRegExp = /\D/;
	var prefixLengthIsValid = false;
	var cardNumbersOnly = cardNumber.replace(/ /g, "");
		
	if (!ccCheckRegExp.test(cardNumbersOnly))
	{
		var prefixRegExp = /^$/;

		switch(cardNumbersOnly.charAt(0))
		{
			case "6":
				//DISCOVER
				prefixRegExp = /^6011\d{12}$/;
				break;

			case "5":
				//MASTERCARD DINERS COMBINED
				prefixRegExp = /^((5[1-5]\d{14})|(3((0[0-5])\d{11}|6\d{12}|8\d{12})))$/;
				break;

			case "4":
				//VISA
				prefixRegExp = /^4(\d{12}|\d{15})$/;
				break;

			case "3":
				if (cardNumbersOnly.length == 14)
				{
					//MASTERCARD DINERS COMBINED
					prefixRegExp = /^(3((0[0-5])\d{11}|6\d{12}|8\d{12}))$/;
				}
				else
				{
					//AMEX
					prefixRegExp = /^3(4|7)\d{13}$/;
				}
				break;
				
			case "1":
				//UATP
				prefixRegExp = /^1\d{14}$/;
				break;
		}

		prefixLengthIsValid = prefixRegExp.test(cardNumbersOnly);
	}

	if (prefixLengthIsValid)
	{
		var numberProduct;
		var checkSumTotal = 0;
		
		while (cardNumbersOnly.length < 16)
		{
			cardNumbersOnly = '0' + cardNumbersOnly;
		}

		for (digitCounter = cardNumbersOnly.length - 1; 0 <= digitCounter; digitCounter -= 2)
		{
			checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
			numberProduct = String((cardNumbersOnly.charAt(digitCounter - 1) * 2));
			for (var productDigitCounter = 0; productDigitCounter < numberProduct.length; productDigitCounter++)
			{
				checkSumTotal += parseInt(numberProduct.charAt(productDigitCounter));
			}
		}

		return (checkSumTotal % 10 == 0);
	}

	return false;
}

function validateNumeric(number)
{
	number = number.replace(/\s/g, '');
	
	if (!number.match(this.numericPattern))
	{
		return false;
	}
	
	return true;
}

function validate(controlID, elementName)
{
	
	//make sure we can run this javascript
 	if (document.getElementById && document.createTextNode)
	{
		var validate = new Validate(document['SkySales'], controlID + '_', errorsHeader);
		
		if (elementName)
		{
			var element = document.getElementById(controlID + "_" + elementName);
			if (element == null) return true;
			
			validate.validateSingleElement(element);
			return validate.outputErrors();
		}
		
		return validate.run();
	}
  	
  	// could not use javascript rely on server validation
  	return true;
}

// </validation_javascript>

// <balanceHeight_javascript>

function balanceHeight(idContainer, idLeft, idRight)
{
	if (document.getElementById)
	{
		hLeft 	= document.getElementById(idLeft).clientHeight;
		hRight  = document.getElementById(idRight).clientHeight;
		if (hLeft > hRight)
		{
			document.getElementById(idContainer).style.height = hLeft + "px";
		}
	}
}

// </balanceHeight_javascript>

