/**
 * @author kma
 * $Id: //depot/Javascripts/common/YM_Validation.js#32 $
 */

/**
 * Messages
 */
var _YM_ZipMissingError = 'Please enter zip code.';
var _YM_CodeFormatError = 'Code Error: Please enter only digits in text boxes.';
var _YM_CodeMissingError = 'Code Error: Please enter a 24-digit code.';

/**
 * HarvestMark Partner: Validation Box Setting
 */
var _YM_Box_Size = 'Regular'; // Small:Regular
var _YM_Partner = false;      // Are we on partner's site

/**
 * overload for generating 6-box-input only (without zip and labels) 
 *
 **/
function YM_renderValidationBoxes(frm,fld,fldCSS,btnImgOrText,btnCSS,btnAtBottom, btnImgMouseOver)
{
    YM_renderValidationBoxes(frm,fld,fldCSS,btnImgOrText,btnCSS,btnAtBottom, btnImgMouseOver, false, null, false)
}

function YM_renderValidationBoxes(frm,fld,fldCSS,btnImgOrText,btnCSS,btnAtBottom, btnImgMouseOver, isZipTextBox, labelCSS, isZipRequired)
{
	YM_renderValidationBoxes(frm,fld,fldCSS,btnImgOrText,btnCSS,btnAtBottom, btnImgMouseOver, isZipTextBox, labelCSS, isZipRequired, false);
}

/**
 * @param frm        	(required): [NO LONGER NEEDED] name of the form
 * @param fld        	(required): prefix for text field
 * @param fldCSS     	(optional): style for text field (this is a inline style, we may need it to overwrite some CSS defined in HTML
 * @param btnImgOrText  (required): full path of the button image or the name of the button. It detects by the matching /\.[a-zA-Z]{3}$/i
 * @param btnCSS     	(optional): style for button
 * @param btnAtBottom	(required): render the submit button below text boxes
 * @param btnImgMouseOver(optional):the image file name for "mouseover" image. null can be used
 * @param isZipTextBox  (optional): control if the zip code textbox is rendered
 * @param labelCSS      (optional): style for the text label
 * @param isZipRequired (optional): control if the zip code is required when submission
 * @param labelOnLeft             : true/false render text label on left instead of above textboxes
 * 
 */
function YM_renderValidationBoxes(frm,fld,fldCSS,btnImgOrText,btnCSS,btnAtBottom, btnImgMouseOver, isZipTextBox, labelCSS, isZipRequired, labelOnLeft)
{
	document.write('<table border="0">');

	frm = escape(frm);

	btnImgOrText = escape(btnImgOrText);
	btnCSS = escape(btnCSS);
	fld = escape(fld);
	fldCSS = escape(fldCSS);
	labelCSS = escape(labelCSS);

	// Style HTML for Button and Field
	if (btnCSS != undefined && btnCSS != 'null' && btnCSS != '')
	{
		btnCSSText = ' class="' + btnCSS + '" ';
	} else {
		btnCSSText = '';
	}
	
	if (fldCSS != undefined && fldCSS != 'null' && fldCSS != '')
	{
		fldCSSText = ' class="' + fldCSS + '" ';
	} else {
		fldCSSText = '';
	}

	if (labelCSS != undefined && labelCSS != 'null' && labelCSS != '')
	{
		labelCSSText = ' class="' + labelCSS + '" ';
	} else {
		labelCSSText = '';
	}

	// image button or regular button
	var btnHTML = '';
	if (YM_IsImageFileNameOrText(btnImgOrText) || btnImgOrText == 'YM_BOX')
	{
		if (btnImgOrText == 'YM_BOX')
		{
			btnHTML += '<img border="0" alt="Submit" src="http://www.yottamark.com/images/partner/trace_btn.gif" ';
		} else 
		{
			btnHTML += '<img border="0" alt="Submit" src="'+btnImgOrText+'" ';
		}
		
		if (YM_IsImageFileNameOrText(btnImgMouseOver))
		{   
		    //btnHTML += 'onmouseover="this.src=';
		    btnHTML += 'onmouseover="this.src=\'' + btnImgMouseOver + '\'" onmouseout="this.src=\''+ btnImgOrText + '\'"';
		}
	} 
	else 
	{
		btnHTML += '<input type="button" value="' + btnImgOrText + '"';
	}
	// finish the button
	btnHTML += btnCSSText + ' onClick="YM_ValidateFields(\''+frm+'\',\''+fld+'\','+isZipRequired+')">';

    if(isZipTextBox)
    {
        document.write('<!-- YM: Zip box Begins -->');
        YM_renderZip(labelCSS, fldCSS, labelOnLeft);
        document.write('<!-- YM: Zip box Ends -->');
    }

    if (labelOnLeft) { document.write('<tr><td style="padding:0px; border:none; text-align:right;"><div '+labelCSSText+'>Enter the 24-digit code:</div>'); }
    else { document.write('<tr><td style="padding:0px; border:none; text-align:left;"><div '+labelCSSText+'>Enter the 24-digit code:</div>');  }
	
	if (labelOnLeft) { document.write('</td><td style="padding:0px; border:none; text-align:left;">'); }
	else { document.write('</td></tr><tr><td style="padding:0px; border:none; text-align:left;">'); }
    
    //Logic to out put different SIZE of input text based on different browsers. There may be more generic solution to avoid this browser-specific coding
    //
    var textBoxSize = 1;
    switch(YM_BrowserDetect.browser)
    {
        case "Safari": textBoxSize = 4; break;
        default: textBoxSize = 1; break;
    }

	document.write('<!-- YM: Validation Boxes Begin -->');
	document.write('<input '+fldCSSText+' type="text" name="ym_'+fld+'1" id="ym_'+fld+'1" value="" tabindex="101" size="'+textBoxSize+'" maxlength="29" onKeyDown="return YM_switchTextBox(event, this);"> ');
	document.write('<input '+fldCSSText+' type="text" name="ym_'+fld+'2" id="ym_'+fld+'2" value="" tabindex="102" size="'+textBoxSize+'" maxlength="29" onKeyDown="return YM_switchTextBox(event, this);"> ');
	document.write('<input '+fldCSSText+' type="text" name="ym_'+fld+'3" id="ym_'+fld+'3" value="" tabindex="103" size="'+textBoxSize+'" maxlength="29" onKeyDown="return YM_switchTextBox(event, this);"> ');
	
	document.write('</td></tr><tr><td style="padding:0px; border:none; text-align:left;">');
	if (labelOnLeft) {	document.write('&nbsp;</td><td style="padding:0px; border:none; text-align:left;">'); }
	
	document.write('<input '+fldCSSText+' type="text" name="ym_'+fld+'4" id="ym_'+fld+'4" value="" tabindex="104" size="'+textBoxSize+'" maxlength="29" onKeyDown="return YM_switchTextBox(event, this);"> ');
	document.write('<input '+fldCSSText+' type="text" name="ym_'+fld+'5" id="ym_'+fld+'5" value="" tabindex="105" size="'+textBoxSize+'" maxlength="29" onKeyDown="return YM_switchTextBox(event, this);"> ');
	document.write('<input '+fldCSSText+' type="text" name="ym_'+fld+'6" id="ym_'+fld+'6" value="" tabindex="106" size="'+textBoxSize+'" maxlength="29" onKeyDown="return YM_switchTextBox(event, this);"> ');
	
	if (labelOnLeft) 
	{	
		if (btnAtBottom)
		{
			document.write('</td></tr><tr><td>&nbsp;</td><td  style="padding:0px; border:none; text-align:left;">'); 
			document.write(btnHTML);
		} else 
		{
			document.write(btnHTML);
		}
	} else 
	{
		if (btnAtBottom)
		{
			document.write('<br />'+btnHTML);
		} else
		{
			document.write(btnHTML);
		}
	}
			document.write('</td></tr>');

	document.write('<!-- YM: Validation Boxes End -->');
	// put focus on first text box
	//eval('document.'+frm+'.ym_'+fld+'1.focus()');
	
	if (isZipTextBox && isZipRequired) 
	{   
	    YM_GetElement('ym_zip').focus();
	} 
	else
	{   
	    // put focus on first text box
		YM_GetElement('ym_'+fld+'1').focus();
	}
	document.write('</table>');
    // Clear fields
    YM_ClearFields(fld);
}

/**
 * 
 *
 */
function YM_ValidateFields(frm,fld, isZipRequired)
{
	frm = escape(frm);
	fld = escape(fld);
	
	var msg = '';
	var mergedField = '';
		var zipcode='';

	if (isZipRequired) 
	{   
	    var zip =  YM_GetElement('ym_zip');
	    if (zip != undefined || zip != null)
	    {
	        zipcode = zip.value;
	    }
	    if ( !YM_CheckZip(zipcode) ) 
	    {
	        zip.focus();
	        return;
	    }
	}
	
	var f1 = YM_GetElement('ym_'+fld+'1');
	var f2 = YM_GetElement('ym_'+fld+'2');
	var f3 = YM_GetElement('ym_'+fld+'3');
	var f4 = YM_GetElement('ym_'+fld+'4');
	var f5 = YM_GetElement('ym_'+fld+'5');
	var f6 = YM_GetElement('ym_'+fld+'6');

	if (f1 != undefined || f1 != null)
	{
		mergedField += f1.value;
		msg += "\nField #1:" + f1.value;
	}
	if (f2 != undefined || f2 != null)
	{
		mergedField += f2.value;
		msg += "\nField #2:" + f2.value;
	}
	if (f3 != undefined || f3 != null)
	{
		mergedField += f3.value;
		msg += "\nField #3:" + f3.value;
	}
	if (f4 != undefined || f4 != null)
	{
		mergedField += f4.value;
		msg += "\nField #4:" + f4.value;
	}
	if (f5 != undefined || f5 != null)
	{
		mergedField += f5.value;
		msg += "\nField #5:" + f5.value;
	}
	if (f6 != undefined || f6 != null)
	{
		mergedField += f6.value;
		msg += "\nField #6:" + f6.value;
	}

	if (YM_CheckCodeFormat(mergedField))
	{   
		if (_YM_Partner)
		{
			window.open('http://harvestmark.com/'+escape(mergedField),'ymWin');
		} else {
			var loc = window.location;
			if (loc.pathname.indexOf(".htm") > 0)
			{
				var newLoc = loc.pathname.substr(0,loc.pathname.lastIndexOf('/')+1);
				window.location = loc.protocol + '//' + loc.host + newLoc + '?Code=' + escape(mergedField);
			} else {
				window.location = window.location + '?Code=' + escape(mergedField);
			}
		}
	}
	else
	{   
	    // put focus on first text box
		YM_GetElement('ym_'+fld+'1').focus();
	}
}

/**
 * Validate zip
 *
 */
function YM_CheckZip(zipcode)
{   
	if (zipcode=='' || zipcode == null)
	{   
		YM_ValidationMessage(_YM_ZipMissingError);
		return false;
	}  
	else 
	{
		return true;
	}
}

/**
 * Validate Code Format
 *
 */
function YM_CheckCodeFormat(code)
{
    //replace spaces
    var codeCompactForm = code.replace(/\s/g,"");
    
	//if (isNaN(codeCompactForm))
	//{
	//	YM_ValidationMessage(_YM_CodeFormatError);
	//	return false;
	//} else if (codeCompactForm.length != 24) {
        if (codeCompactForm.length < 16) {
		YM_ValidationMessage(_YM_CodeMissingError);
		return false;
	} else {
		return true;
	}
}

/**
 * Wrapper for displaying message onscreen
 *
 **/
function YM_ValidationMessage(m)
{
	alert(m + '\n\n' + 'Click OK to continue.');
}

/**
 * 
 *
 **/
function YM_IsImageFileNameOrText(name)
{   //test the file extension for the file
    var pattern = /\.[a-zA-Z]{3}$/i;
	return pattern.test(name);
}

/**
 * generate inner HTML text for rendering zip and labels
 *
 **/
function YM_getZip(labelCSS, fldCSS, labelOnLeft)
{
    var innerHTMLText = '';
    labelCSS = escape(labelCSS);
	fldCSS = escape(fldCSS);
	
	if (labelCSS != undefined && labelCSS != 'null' && labelCSS != '')
	{
		labelCSSText = ' class="' + labelCSS + '" ';
	} else {
		labelCSSText = '';
	}
	
	if (fldCSS != undefined && fldCSS != 'null' && fldCSS != '')
	{
		fldCSSText = ' class="' + fldCSS + '" ';
	} else {
		fldCSSText = '';
	}
    
    if (labelOnLeft) { innerHTMLText = '<tr><td style="padding:0px; border:none; text-align:right;">'; }
    else { innerHTMLText = '<tr><td style="padding:0px; border:none; text-align:left;">'; }
    
    innerHTMLText += '<div '+labelCSSText+'> Enter Zip Code: </div>';
	
	if (labelOnLeft) { innerHTMLText += '</td><td style="padding:0px; border:none; text-align:left;">'; }
	else { innerHTMLText += '</td></tr><tr><td style="padding:0px; border:none; text-align:left;">'; }

    innerHTMLText += '<input '+fldCSSText+' type="text" name="ym_zip" id="ym_zip" value="" tabindex="100" size="10" maxlength="10" >';

	innerHTMLText += '</td></tr>'; 
	
    return innerHTMLText;
}

/**
 * 
 *
 **/
function YM_renderZip(labelCSS, fldCSS, labelOnLeft)
{
    document.write(YM_getZip(labelCSS, fldCSS, labelOnLeft));
}

//To break 24-digital YM code into 6 groups, use this JS function
/**
 * 
 *
 */
function YM_switchTextBox(e, currentTextBox) 
{
    if (YM_processPrefix(e)) 
    {
	    var currentTextBoxName = currentTextBox.name;
	    var index = parseInt(currentTextBoxName.substring(currentTextBoxName.length-1))
	    var preTextBoxName = currentTextBoxName.substring(0,currentTextBoxName.length-1)+(index-1);
	    var nextTextBoxName = currentTextBoxName.substring(0,currentTextBoxName.length-1)+(index+1);
	    var preTextBox = YM_GetElement(preTextBoxName);
	    var nextTextBox = YM_GetElement(nextTextBoxName);
	    //deal with arrow-keys to be able to across boundry
	    //Note: In general, if it return false, the key input doesn't get accepted, but it's not true for at least
	    //      "left arrow" and "right arrow" keys. And actually, "false" has to be returned to make "left arrow" 
	    //      to work between boxes in IE. I don't know why it's this way.
	    if (YM_doGetCaretPosition(currentTextBox) == 0 && YM_isLeftArrow(e)) 
	    {
	        if (preTextBox != null) 
	        {
	            YM_setCaretPosition(preTextBox, preTextBox.value.length);
	            return false; //IE doesn't work if returning true.
	        }
	    }
	    
	    if (YM_doGetCaretPosition(currentTextBox) == currentTextBox.value.length && YM_isRightArrow(e)) 
	    {
	        if (nextTextBox != null) 
	        {
	            YM_setCaretPosition(nextTextBox, 0);
	            return false; //not necessary, just to match LeftArrow
	        }
	    }
	     
	    //deal with "Backspace"
	    //at the beginning of the text field, if "backspace" is pressed, the cursor should go back to the previous textbox and delete one charactor.
	    if (YM_doGetCaretPosition(currentTextBox) == 0 && YM_isBackSpace(e)) 
	    {
	        if (preTextBox != null) YM_setCaretPosition(preTextBox, preTextBox.value.length);
	    }
	    
	    if (currentTextBox.value.length == 3 && YM_isDigit(e) && YM_doGetCaretPosition(currentTextBox) == 3) 
	    {
	        currentTextBox.value += YM_getKeyChar(e);
	        
	        if (nextTextBox != null) nextTextBox.focus();
	        return false;
	    }
	    return true;
    }
    else 
    {
        return false;
    }
}



//taken from online http://www.tek-tips.com/viewthread.cfm?qid=1226446&page=1
function YM_doGetCaretPosition (ctrl) 
{	
    var CaretPos = 0;	
    // IE Support	
    if (document.selection) {		
        ctrl.focus ();		
        var Sel = document.selection.createRange ();		
        Sel.moveStart ('character', -ctrl.value.length);		
        CaretPos = Sel.text.length;	
    }	
    // Firefox support	
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')		
        CaretPos = ctrl.selectionStart;	

    return (CaretPos);
}

//taken from online http://www.tek-tips.com/viewthread.cfm?qid=1226446&page=1
function YM_setCaretPosition(ctrl, pos)
{	
    if(ctrl.setSelectionRange)	
    {		
        ctrl.focus();		
        ctrl.setSelectionRange(pos,pos);	
    }	
    else if (ctrl.createTextRange) 
    {		
        var range = ctrl.createTextRange();		
        range.collapse(true);		
        range.moveEnd('character', pos);		
        range.moveStart('character', pos);		
        range.select();	
    }
}

//To preprocess data on client site before submission
function YM_processPrefix(e)
{   
    var keyNum = YM_getKeyNum(e);

    if (
        (e.shiftKey) && ( keyNum >= 48 &&  keyNum <= 57 )  || //! @ # $ % ^ & * ( )
        (!e.ctrlKey) && ( keyNum >= 65 &&  keyNum <= 90 )  ||
        ( keyNum >= 186 &&  keyNum <= 192 ) || //; = , - . / `
        ( keyNum >= 219 &&  keyNum <= 222 ) || //[ \ ] '
        ( keyNum >= 106 &&  keyNum <= 111 ) || //* + - . /
         keyNum == 32 //space
        )
        {
            return false;
        }
        else 
        {
            return true;
        }
}

function YM_isSpace(e)
{   
       if ( YM_getKeyNum(e) == 32 ) 
    { 
        return true;
    }
    else
    {   
        return false;
    }
}

function YM_isBackSpace(e)
{   
    if ( YM_getKeyNum(e) == 8 ) 
    { 
        return true;
    }
    else
    {   
        return false;
    }
}

function YM_isLeftArrow(e)
{   
       if ( YM_getKeyNum(e) == 37 ) 
    { 
        return true;
    }
    else
    {   
        return false;
    }
}

function YM_isRightArrow(e)
{   
       if ( YM_getKeyNum(e) == 39 ) 
    { 
        return true;
    }
    else
    {   
        return false;
    }
}

function YM_isEnterKey(e)
{   
    //alert(YM_getKeyNum(e));
    if ( YM_getKeyNum(e) == 13 ) 
    { 
        return true;
    }
    else
    {   
        return false;
    }
}

function YM_isDigit(e)
{   
    var keyNum = YM_getKeyNum(e);
    var checkChar = /\d/ //digits
    if (keyNum >= 96 && keyNum <= 105) return true;
    return checkChar.test(YM_getKeyChar(e));
}

function YM_getKeyNum(e)
{
    var keyNum;
    if(window.event) // IE
    {
        keyNum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keyNum = e.which;
    }
    return keyNum;
}

function YM_getKeyChar(e)
{
    //hack to get numerics to work
    var keyNum = YM_getKeyNum(e);
    if (keyNum >= 96 && keyNum <= 105) return String.fromCharCode(YM_getKeyNum(e)-48);
    
    return String.fromCharCode(YM_getKeyNum(e));
}

//Note: "Stack overflow" JS error occurs when trying to overload YM_submit method; so a different name is used
function YM_submit1(e, frm, fld, isZipRequired)
{
    if (YM_isEnterKey(e)) YM_ValidateFields(frm, fld, isZipRequired);
}

function YM_submit(e, frm, fld)
{
    YM_submit1(e, frm, fld, false)
}

/**
 * Partner Box
 *
 */
function YM_Partner_Validation()
{
	var _frm = 'ymf1';
	_YM_Partner = true;
	
	if (document.forms.count == undefined)
	{
		_YM_Box_Form = false;
		_YM_Form_Count = 0;
	} else {
		_YM_Form_Count = document.forms.count;

		if (document.forms[(_YM_Form_Count-1)].name == undefined)
		{
			document.forms[(_YM_Form_Count-1)].name = _frm;
		} else {
			_frm = document.forms[(_YM_Form_Count-1)].name;
		}
	}
	document.write('<style>');
	if (_YM_Box_Size == "Regular")
	{
		document.write('.ymbtr { background-image: url(http://www.yottamark.com/images/partner/r_bg.gif); font-family:Arial, Helvetica, sans-serif; font-size: small; } .ymfont {font-family:Arial, Helvetica, sans-serif; font-size: small;}');
	} else {
		document.write('.ymbtr { background-image: url(http://www.yottamark.com/images/partner/s_bg.gif); font-family:Arial, Helvetica, sans-serif; font-size: small; } .ymfont {font-family:Arial, Helvetica, sans-serif; font-size: small;}');
	}
	document.write('.ymbsp { width: 2px; }');
	document.write('</style>');
	if (_YM_Box_Size == "Regular")
	{
		document.write('<table width="209" cellpadding="0" cellspacing="0" border="0">');
	} else {
		document.write('<table width="133" cellpadding="0" cellspacing="0" border="0">');
	}
	document.write('<tr valign="bottom">');
	if (_YM_Box_Size == "Regular")
	{
		document.write('<td valign="bottom" colspan="3"><img src="http://www.yottamark.com/images/partner/r_top.gif" border="0" width="209" height="11" align="absbottom">');
	} else {
		document.write('<td valign="bottom" colspan="3"><img src="http://www.yottamark.com/images/partner/s_top.gif" border="0" width="133" height="10" align="absbottom">');
	}
	document.write('</tr>');
	document.write('<tr class="ymbtr">');
	document.write('<td width="2" class="ymbsp"></td>');
	if (_YM_Box_Size == "Regular")
	{
		document.write('<td align="center"><img src="http://www.yottamark.com/images/partner/HM_JS_Btn.jpg"></td>');
	} else {
		document.write('<td align="center"><img src="http://www.yottamark.com/images/partner/HM_JS_Btn_s.jpg" align="center"></td>');
	}
	document.write('<td width="2" class="ymbsp"></td>');
	document.write('</tr>');
	document.write('<tr class="ymbtr">');
	document.write('<td width="2" class="ymbsp"></td>');
	document.write('<td align="center">');
	document.write('<table border="0" cellpadding="3" cellspacing="0"><tr><td>');
	document.write('<script type="text/javascript">');
	if (_YM_Box_Size == "Regular")
	{
		document.write('YM_renderValidationBoxes("'+_frm+'", "CodePart", "", "YM_BOX",null, false, null, false, "ymfont", false,false);');
	} else {
		document.write('YM_renderValidationBoxes("'+_frm+'", "CodePart", "", "YM_BOX",null, true, null, false, "ymfont", false,false);');
	}
	document.write('</script>');
	document.write('</td></tr></table>');
	document.write('</td>');
	document.write('<td width="2" class="ymbsp"></td>');
	document.write('</tr>');
	document.write('<tr valign="top">');
	if (_YM_Box_Size == "Regular")
	{
		document.write('<td valign="top" colspan="3"><img src="http://www.yottamark.com/images/partner/r_bottom.gif" border="0" width="209" height="11" align="top"></td>');
	} else {
		document.write('<td valign="top" colspan="3"><img src="http://www.yottamark.com/images/partner/s_bottom.gif" border="0" width="133" height="10" align="top"></td>');
	}
	document.write('</tr>');
	document.write('</table>');
} 

function YM_ClearFields(fld)
{
	var f1 = YM_GetElement('ym_'+fld+'1');
	var f2 = YM_GetElement('ym_'+fld+'2');
	var f3 = YM_GetElement('ym_'+fld+'3');
	var f4 = YM_GetElement('ym_'+fld+'4');
	var f5 = YM_GetElement('ym_'+fld+'5');
	var f6 = YM_GetElement('ym_'+fld+'6');

	if (f1 != undefined || f1 != null)
	{
		f1.value = '';
	}
	if (f2 != undefined || f2 != null)
	{
		f2.value = '';
	}
	if (f3 != undefined || f3 != null)
	{
		f3.value = '';
	}
	if (f4 != undefined || f4 != null)
	{
		f4.value = '';
	}
	if (f5 != undefined || f5 != null)
	{
		f5.value = '';
	}
	if (f6 != undefined || f6 != null)
	{
		f6.value = '';
	}
}
