/**
 * This is a common Javascript file
 * used in PRM Portal
 * Copyright Wipro Technologies Limited
 */

/**
*  This function checks whether 
*  a value is selected in a 
*  multi select box
*/

function checkComboBoxSelection(listBoxId)
{
	var listBox = document.getElementById(listBoxId);
	var len = listBox.length;

	var optionSelected = false;
	for(i=0;i<len;i++)
	{
		if(listBox.options[i].selected)
		{
			optionSelected = true; break;
		}
	}
	return optionSelected;
}
function clearListBoxSelection(listBoxId)
{
	var listBox = document.getElementById(listBoxId);
	var len = listBox.length;

	for(i=0;i<len;i++)
	{
		if(listBox.options[i].selected)
		{
			listBox.options[i].selected = false;
		}
	}
}

/**
*  This function copies
*  values from Source ListBox 
*  into Destination ListBox
*/

function copyValues(srcListBoxId, destListBoxId)
{
	var srcListBox = document.getElementById(srcListBoxId);
	var len = srcListBox.length;
	var destListBox = document.getElementById(destListBoxId);

	var optionSelected = checkComboBoxSelection(srcListBoxId);
	
	if(optionSelected == false)
	{ alert("Please select a value to Copy"); return false; }
	else
	{
		for(var j=0; j<len; j++)
		{
			if(srcListBox.options[j].selected)
			{  
				var tmp = srcListBox.options[j].text;
				var tmp1 = srcListBox.options[j].value;
				if ( !recheck (tmp, destListBox) ){
					
					srcListBox.remove(j);
					j--;
					var y=document.createElement('option');
					y.text=tmp;
					y.value=tmp1;
					try
					{
						destListBox.add(y,null);
					}
					catch(ex)
					{
						destListBox.add(y);
					}
					len--;
				}else{
					alert("Option is already present");
				 }	
			}
		}
		
	}
	//Sort the listboxes
	//sortListBox(srcListBoxId);	
	return false;
}
/**
*  This function copies
*  values from Source ListBox 
*  into Destination ListBox
*/

function removeValues(srcListBoxId, destListBoxId)
{
	var srcListBox = document.getElementById(srcListBoxId);
	var len = srcListBox.length;
	var destListBox = document.getElementById(destListBoxId);

	var optionSelected = checkComboBoxSelection(srcListBoxId);
	
	if(optionSelected == false)
	{ alert("Please select a value to Copy"); return false; }
	else
	{
		for(var j=0; j<len; j++)
		{
			if(srcListBox.options[j].selected)
			{  
				var tmp = srcListBox.options[j].text;
				var tmp1 = srcListBox.options[j].value;
				srcListBox.remove(j);
				j--;
				var y=document.createElement('option');
				y.text=tmp;
				y.value=tmp1;
				try
				{
					destListBox.add(y,null);
				}
				catch(ex)
				{
					destListBox.add(y);
				}
				len--;
			}
		}
		
	}
	//Sort the listboxes
	//sortListBox(srcListBoxId);	
	return false;
}
function recheck (selectObject, optionText){
	var sltbool = false;
	for (j=0; j<optionText.options.length; j++)
	{
		if (selectObject == optionText.options[j].text)
		{
			sltbool = true;
			break
		}
	 }
	  return sltbool;
}
/**
*  This function sorts
*  all the values present in a ListBox 
*/

function sortListBox(listBoxId)
{
	var listBox = document.getElementById(listBoxId);
	var textArray=new Array();
	var valueArray=new Array();

	for (i=0;i<listBox.options.length;i++) 
	{
		textArray[i] = listBox.options[i].text;
		valueArray[i] = listBox.options[i].value;
	}
	textArray.sort();
	valueArray.sort();

	for (i=0;i<textArray.length;i++) 
	{
		listBox.options[i].text = textArray[i];
		listBox.options[i].value = valueArray[i];
	}
}

/**
*  This function sorts
*  creates comma seperated values
*  of all the values selected in a listbox
*  and stores them in an input hidden field
*/

function createCommaSeperatedValues(destListBoxId,inputBoxId)
{
	var destListBox = document.getElementById(destListBoxId);
	var inputBox = document.getElementById(inputBoxId);
	for (i=0;i<destListBox.options.length;i++) 
	{		
		if(inputBox.value == "")
		{ 
			inputBox.value = destListBox.options[i].value;
		}
		else
		{
			inputBox.value =  inputBox.value+ "," + destListBox.options[i].value;
		}
	}
}

/**
*  This function 
*  stores the  
*  filename of the selected file
*  in a hidden field
*/

function uploadFile(fileElementId)
{
	if(fileElementId != "")
	{
		var fileElement = document.getElementById(fileElementId);
		if(fileElement.value != "")
		{
			var filePath= fileElement.value;
			var names=	filePath.split("\\");
			var fileName = names[names.length-1];
			document.getElementById("hidden"+fileElementId).value=fileName;
			//document.getElementById("hidden"+fileElementId).value=fileElement.value;
		}
	}
}

function uploadFile1(fileElementId)
{
	if(fileElementId != "")
	{
		var fileElement = document.getElementById(fileElementId);
		if(fileElement.value != "")
		{
			/*var filePath= fileElement.value;
			var names=	filePath.split("\\");
			var fileName = names[names.length-1];
			document.getElementById("hidden"+fileElementId).value=fileName;*/
			document.getElementById("hidden"+fileElementId).value=fileElement.value;
		}
	}
}

/**
*  This function 
*  Trims the value of 
*  the input String
*/

function Trim(str)
{ 
	while(str.charAt(0) == (" ") )
	{ 
		str = str.substring(1);
	}
	while(str.charAt(str.length-1) == " " )
	{ 
		str = str.substring(0,str.length-1);
	}
	return str;
}

/**
*  This function 
*  sorts and selects the
*  values in the list box
*  based on the String input
*  in a text box
*/

/*function selectListBoxValues(listBoxId,textBoxId)
{
	var searchString = document.getElementById(textBoxId).value;
	var listBox = document.getElementById(listBoxId);
	var length = searchString.length;
	for(i=0;i<listBox.options.length;i++)
	{
		var strCompare = listBox.options[i].value;//.substring(0, searchString.length);
		if((Trim(strCompare) !=null) && (searchString==strCompare))
		{
			listBox.options[i].selected = true;
			break;
		}
	}
}*/
/**
*  This function 
*  sorts and selects the
*  values in the list box
*  based on the String input
*  in a text box
*/

function selectListBoxValues(listBoxId,textBoxId)
{
	clearListBoxSelection(listBoxId);
	var searchString = Trim(document.getElementById(textBoxId).value.toLowerCase());
	var listBox = document.getElementById(listBoxId);
	//Sort and select based on Search String
	sortListBox(listBoxId);
	
	for (i=0;i<listBox.options.length;i++) 
	{ 
		var listBoxText = Trim(listBox.options[i].text.toLowerCase());
		if(listBoxText.search(searchString)==-1) { }
		else { 
		//alert("String exists"); 
		//Highlight the String and break
		listBox.options[i].selected = true;
		break;
		}
	}

}
/**
*  This function is used for get respective content 
*  page on selection of the particular content type
*  in home page of create content.
*/

function loadContentType(formId,selectedValue)
{
	document.getElementById(formId).action = document.getElementById(selectedValue).value;
	document.getElementById(formId).submit();
}
/**
*  This function is used for submit the form of selected 
*  Item Type to create that particular content type.
*/
function callsubmitForm(formId,pageId)
{	
	
	
	var errorMessage = "";
	
	if(pageId==1){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	//errorMessage += validateMandatoryFields('displayDate');
	//errorMessage += validateMandatoryFields('publicationName');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');
	//errorMessage += validateMandatoryFields('author');
	errorMessage += validateMandatoryFields('par');
	errorMessage += validateMandatoryFields('uploadContent');
	errorMessage += isDateCheck('displayDate');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	errorMessage += compareThreeDates('startDate','expirationDate','displayDate');	
	//As per Adiga's request
	/*if(document.getElementById('brands') != null && document.getElementById('brands').checked){
	errorMessage += validateAssignedBrandField('selectedBrandList');
	}*/
	}
	
	if(pageId==2){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');
	errorMessage += validateMandatoryFields('par');
	errorMessage += validateMandatoryFields('uploadContent');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += compareDates('startDate','expirationDate');	
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	//As per Adiga's request
	/*if(document.getElementById('brands') != null && document.getElementById('brands').checked){
		errorMessage += validateAssignedBrandField('selectedBrandList');
	}*/
	}

	if(pageId==3){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');
	//errorMessage += validateMandatoryFields('question');
	//errorMessage += validateMandatoryFields('answer');
	errorMessage += validateMandatoryFields('faqhtmlContent');
	errorMessage += validateMandatoryFields('par');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += compareDates('startDate','expirationDate');
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	errorMessage += isMaxLengthForHtml('faqhtmlContent',12000);
	}
	
	if(pageId==4){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');
	errorMessage += validateMandatoryFields('url');	
	errorMessage += validateMandatoryFields('par');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += compareDates('startDate','expirationDate');
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	//As per Adiga's request
	/*if(document.getElementById('brands') != null && document.getElementById('brands').checked){
		errorMessage += validateAssignedBrandField('selectedBrandList');
	}*/
	}

	if(pageId==5){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');
	errorMessage += validateMandatoryFields('contactName');	
	//errorMessage += validateMandatoryFields('contactEmail');
	errorMessage += validateMandatoryFields('contactPhone');
	//errorMessage += validateMandatoryFields('par');
	//errorMessage += validateMandatoryFields('url');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += compareDates('startDate','expirationDate');	
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	errorMessage += validateEmail('contactEmail');
	}

	if(pageId==6){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');
	errorMessage += validateMandatoryFields('meetingStartDate');	
	errorMessage += validateMandatoryFields('meetingEndDate');
	errorMessage += validateMandatoryFields('venue');
	errorMessage += validateMandatoryFields('address1');
	errorMessage += validateMandatoryFields('city');
	errorMessage += validateMandatoryFields('state');	
	errorMessage += validateMandatoryFields('country');
	errorMessage += validateMandatoryFields('zip');
	errorMessage += validateMandatoryFields('meetingwebsite');
	errorMessage += validateMandatoryFields('par');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += compareDates('startDate','expirationDate');	
	errorMessage += compareDates('meetingStartDate','meetingEndDate');
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	}

	if(pageId==7){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	errorMessage += validateMandatoryFields('vendor');
	errorMessage += validateMandatoryFields('vendorUrl');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');
	errorMessage += validateMandatoryFields('programId');
	errorMessage += validateMandatoryFields('par');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += compareDates('startDate','expirationDate');	
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	errorMessage += validateMandatoryFields('uploadLogo');
	// Added for PI CR
	//if(document.getElementById('brands') != null && document.getElementById('brands').checked){
		errorMessage += validateAssignedBrandFieldOneContent('selectedBrandList');
	//}
	}
	
	if(pageId==8){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');
	errorMessage += validateMandatoryFields('vendor');
	errorMessage += validateMandatoryFields('webCode');
	errorMessage += validateMandatoryFields('webId');
	errorMessage += validateMandatoryFields('conferencePassword');
	errorMessage += validateMandatoryFields('webUrl');
	errorMessage += validateMandatoryFields('par');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += compareDates('startDate','expirationDate');
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	// Added for PI CR
	//if(document.getElementById('brands') != null && document.getElementById('brands').checked){
		errorMessage += validateAssignedBrandFieldOneContent('selectedBrandList');
	//}
	}

	if(pageId==9){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');	
	errorMessage += validateMandatoryFields('sampleText');
	//Release3.4 changes
	//errorMessage += validateMandatoryFields('materialText');
	//errorMessage += validateMandatoryFields('uploadLogo1');
	//errorMessage += validateMandatoryFields('uploadLogo2');
	errorMessage += validateMandatoryFields('par');
	errorMessage += validateMandatoryFields('programId');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += compareDates('startDate','expirationDate');
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	// Added for PI CR
	//if(document.getElementById('brands') != null && document.getElementById('brands').checked){
		errorMessage += validateAssignedBrandFieldOneContent('selectedBrandList');
	//}
	}

	if(pageId==10){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');
	errorMessage += validateMandatoryFields('par');
	errorMessage += validateMandatoryFields('htmlContent');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	errorMessage += isMaxLengthForHtml('htmlContent',20000);
	}

	if(pageId==11){
	errorMessage += validateMandatoryFields('title');
	errorMessage += validateMandatoryFields('displayName');
	errorMessage += validateMandatoryFields('startDate');
	errorMessage += validateMandatoryFields('expirationDate');
	errorMessage += validateMandatoryFields('uploadImage');
	errorMessage += validateMandatoryFields('par');
	errorMessage += isDateCheck('startDate');
	errorMessage += isDateCheck('expirationDate');
	errorMessage += validateParNumber('par');
	errorMessage += alphanumericContent('keywords');
	}

	errorMessage += validatePageSpecificFields(pageId);

	if (errorMessage != "") 
	{
		alert("Some fields need correction:\n" + errorMessage);
		return false;
	}
	else
	{
		if(pageId != '5')
		{				
			submitForm('selectedCategoriesList', 'ReturnCategoriesList');	
		}
		submitForm('selectedBrandList', 'ReturnBrandList');
		if (pageId == '1' || pageId == '4' || pageId == '2') {
			submitForm('selectedConditionList', 'ReturnConditionList');
		}
		submitForm('selectedSegmentList', 'ReturnSegmentList');
		if(pageId == '9')
		{	
			submitForm('selectedTreatmentList', 'ReturnTreatmentList');
		}
		document.getElementById(formId).submit();
	}
	
}
/**
*  This function is used for validation of all  
*  the Mandatory fields for create content type.
*/
function validateMandatoryFields(fieldName)
{	
	var errorMessage="";
	
	if(Trim(document.getElementById(fieldName).value)=="")  
	{	
		
	  var errorName=assignErrorField(fieldName);	  	
	   errorMessage += "You must enter a " +errorName+"\n";	   
	   document.getElementById(fieldName).focus();  
	 }
	 return errorMessage;
}

//Start Added for PI CR
/**
*  This function is used for validation of all  
*  the Mandatory fields for create content type.
*/
function validateAssignedBrandField(fieldName)
{	
	var errorMessage="";
	
	if(document.getElementById(fieldName).length>1)  
	{		
		var errorName=assignErrorField(fieldName);	  	
		errorMessage += "You can associate only one Brand with the content\n";	   
		document.getElementById(fieldName).focus();  
	}
	else if(document.getElementById(fieldName).length<1)
	{
		var errorName=assignErrorField(fieldName);	  	
		errorMessage += "You have to associate one Brand with the content\n";	   
		document.getElementById(fieldName).focus();
	}
	return errorMessage;
}

/**
*  This function is used to validate  
*  only one content is associated to a brand.
*/
function validateAssignedBrandFieldOneContent(fieldName)
{	
	var errorMessage="";
	if(document.getElementById(fieldName).length>1)  
	{		
		var errorName=assignErrorField(fieldName);	  	
		errorMessage += "You can associate only one Brand with the content\n";	   
		document.getElementById(fieldName).focus();  
	}
	return errorMessage;
}
// End Added for PI CR
/**
*  This function is used for validation of all  
*  the fields for specific page for create content type.
*/
function validatePageSpecificFields(pageId)
{	
	var errorMessage="";
	if(pageId == '1')
	{		
		/*errorMessage += isNumber('position');
		errorMessage += isNumber('par');
		errorMessage += isNumber('delayTime');
		errorMessage += isNumber('ProgramId');*/
	}
	/*if(pageId == '2' || pageId == '3' || pageId == '4' || pageId == '9' || pageId == '10' || pageId == '11')
	{		
		errorMessage += isNumber('position');
	}*/
	if(pageId == '4')
	{		
		errorMessage += validateWebUrl('url');
	}
	
	if(pageId == '5')
	{		
		//errorMessage += isNumber('position');
		errorMessage += isNumber('contactPhone');
		errorMessage += isNumber('contactFax');
		errorMessage += validateWebUrl('url');
	}
	if(pageId == '6')
	{		
		//errorMessage += isNumber('position');
		errorMessage += isNumber('zip');
		errorMessage += validateWebUrl('meetingwebsite');
	}

	if(pageId == '7')
	{		
		//errorMessage += isNumber('position');
		//errorMessage += isNumber('programId');
		errorMessage += isNumber('channelCode');
		errorMessage += isNumber('gskEmployeeNumber');
		errorMessage += validateWebUrl('vendorUrl');
	}

	if(pageId == '8')
	{		
		//errorMessage += isNumber('position');
		errorMessage += isNumber('webCode');
		errorMessage += isNumber('webId');
		errorMessage += validateWebUrl('webUrl');
	}



	return errorMessage;
}

/**
 * Function to validate a URL
 * if invalid returns true, else return false
 * @return
 */
function validateWebUrl(elementId)
{
	var error="";
	var urlName=document.getElementById(elementId).value;
	if(urlName !="")
	{	
		var tomatch = urlName.toLowerCase().match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%\"\,\{\}\\|\\\^\[\]`]+)?$/);
	    if(tomatch==null)
	  	{
	  		return error += "Please enter a valid URL Name like http://www.abc.com";
	  	}
	}
	return error; 
}
/**
 * Function to check for maxlength of text area
 * on validating, the function will return true or false
 * @param elementId
 * @param maxLength
 * @return
 */

function isMaxLengthForHtml(elementId,maxLength)
{
   var error="";
   var textAreaValue=document.getElementById(elementId).value;
   if(textAreaValue !=""){
	   if(parseInt(document.getElementById(elementId).value.length) > maxLength && document.getElementById(elementId).value!="") 
	   {
		   var errorName=assignErrorField(elementId);
		   return error += "The field " +errorName + " contains more than 20000 Character\n";
	   }
   }
   return error
}
/**
*  This function is used for validation of all  
*  the Numeric fields for create content type.
*/
function isNumber(fieldName)
{
 var error="";
 if(document.getElementById(fieldName).value !="")
 {	
	 var s_len=document.getElementById(fieldName).value.length ; 
	 var s_charcode = 0; 
	 for (var s_i=0;s_i<s_len;s_i++) 
	 { 
		 s_charcode = document.getElementById(fieldName).value.charCodeAt(s_i); 
		 if(!((s_charcode>=48 && s_charcode<=57))) 
		 {
			 errorName=assignErrorField(fieldName);
			 return error += "The field " +errorName + " contains illegal characters.Please enter number only\n";
			 document.getElementById(fieldName).focus(); 
		 }
	 }
 }
return error; 
}

/**
*  This function is used for validation of   
*  the Alphanumeric values.
*/
function alphanumericContent(alphane)
{
	var errorMessage="";
	var numaric = document.getElementById(alphane).value;
	if(numaric !="")
	{	
		//Change- Adding comma is the regular exprssion
		if (numaric.match(/^[a-zA-Z0-9,\s]+$/))
		{ 
			return errorMessage;
		}
		else
		{
			var errorName=assignErrorField(alphane);
			errorMessage += "The field " +errorName+" contains illegal characters.Please enter allphabet or number only\n"; 
			document.getElementById(alphane).focus(); 
			return errorMessage; 
		}
	}
 return errorMessage;
}
/**
*  This function is used for to assign all selected Categories, 
*  Segments and brands value in the page.
*/
function submitForm(destListBoxId, inputBoxId)
{
	var destListBox = document.getElementById(destListBoxId);	
	for (i=0;i<destListBox.options.length;i++) 
	{		
		if(document.getElementById(inputBoxId).value == "")
		{ 
			document.getElementById(inputBoxId).value = destListBox.options[i].value;
		}
		else
		{
			document.getElementById(inputBoxId).value =  document.getElementById(inputBoxId).value+ "," + destListBox.options[i].value;
		}
	}	
}

/**
 * Function validates a text box whether numeric,
 * alphanumeric, alphabet
 * @param txtboxId
 * @param inputType
 * @return
 */
function validateTextBox(txtboxId, inputType)
{
	var txtBox = document.getElementById(txtboxId);
	if(Trim(txtBox.value) != "") //Check if input is Entered
	{
		 
		if(inputType == "numeric")
		{ 
			//Validate if the entered input is Numeric
			if(txtBox.value.match(/^[0-9]+$/))
			{ return true; }
			else
			{ return false; }
		}
		else if(inputType == "alphabet")
		{
			//Validate if the entered input is Alphabet
			if (txtBox.value.match(/^[a-zA-Z\s]+$/))
			{ return true; }
			else
			{ return false; } 
		}
		else if(inputType == "alphanumeric")
		{
			//Validate if the entered input is Alpha Numeric
			if (txtBox.value.match(/^[a-zA-Z0-9\s]+$/))
			{ return true; }
			else
			{ return false; } 
		}
	}
	else
	{  return false; } //If input is not entered
}

/**
 * Function to validate the file extension 
 * types
 * @param fileElementId
 * @param fileType
 * @return
 */
function validateFileExtension(fileElementId,fileType)
{
	var fileName = document.getElementById(fileElementId);
	if(Trim(fileName.value)!="" && !parseInt(Trim(fileName.value).length) < 5)
	{
		if(fileType=="ImageType")
		{
			if(fileName.value.toLowerCase().search(/\.(gif|jpg|jpeg|bmp|3dm|3dmf|ai|drw|dxf|eps|indd|mng|pct|png|tif|ps|psd|psp|qxd|qxp|svg)$/) == -1)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else if(fileType=="PdfType" && !parseInt(Trim(fileName.value).length) < 5)
		{
			if(fileName.value.toLowerCase().search(/\.(pdf)$/) == -1)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else if(fileType=="VideoType" && !parseInt(Trim(fileName.value).length) < 5)
		{
			if(fileName.value.toLowerCase().search(/\.(wma)$/) == -1)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else if(fileType=="Presentation" && !parseInt(Trim(fileName.value).length) < 5)
		{
			if(fileName.value.toLowerCase().search(/\.(ppt)$/) == -1)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	else
	{
		return false;
	}
}

/**
 * Function to check the input type
 * validation
 * @param e
 * @return
 */
function onkeyPress(e)
{
	var key = window.event ? e.keyCode : e.which;
	if (key == 13)
	StartClick();
	e.cancelBubble = true;
	e.returnValue = false;
	return false;
}

/**
 * Function to check for maxlength of text area
 * on validating, the function will return true or false
 * @param elementId
 * @param maxLength
 * @return
 */

function isMaxLengthExceeds(elementId,maxLength)
{
   if(document.getElementById(elementId) != null && parseInt(document.getElementById(elementId).value.length) > maxLength && document.getElementById(elementId).value!="") 
   {
	   return true;
   }
   else
   { 
	   return false; 
   }
}


/**
 * Function to validate a URL
 * if invalid returns true, else return false
 * @return
 */
function validateURL(elementId)
{
	var urlName=document.getElementById(elementId).value;
	var tomatch = urlName.toLowerCase().match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%\"\,\{\}\\|\\\^\[\]`]+)?$/);
    if(tomatch==null)
  	{
  		return true;
  	}
    else
    {
    	return false;
    }
}

/*function validateURL(elementId)
{
	var urlName=document.getElementById(elementId).value;
	var tomatch = urlName.match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%\"\,\{\}\\|\\\^\[\]`]+)?$/);
    if(tomatch==null)
  	{
  		return true;
  	}
    else
    {
    	return false;
    }
}
*/
function commonKeyCapture(evt)
{
	 evt = (evt) ? evt : ((window.event) ? window.event : "")
	 if (evt) {
	 code = (evt.keyCode) ? evt.keyCode : evt.which
	 }
	 if (code == 13)
	 {
		quickSearch('CommerceQuery_SearchField', 'CommerceQuery_SearchFieldValue');
	 }
}

function getTextLength(elementId,maxLength)
{
   if((document.getElementById(elementId).value.length +  window.clipboardData.getData("Text").length) > maxLength) {
	return false;
   }
   else
   { return true; }
} 



/**
* Compare two date
*/

function compareDates(startDate, expirationDate){

	if(startDate!=""&& expirationDate!=""){	
		var error="";
		var statringDate=new Date(document.getElementById(startDate).value);
		var endDate=new Date(document.getElementById(expirationDate).value);
		var currentDate=new Date();
		var month = currentDate.getMonth()	
		var day = currentDate.getDate()
		var year = currentDate.getFullYear()
		var curDate=new Date(year,month,day);

		var errorStartDate=assignErrorField(startDate);
		var errorEndDate=assignErrorField(expirationDate);
		var typeCode = document.getElementById('operationType').value;
		if(typeCode != 'EditContent')
		{
			if(curDate>statringDate){
				error=errorStartDate+" must be greater than or equal to Todays date\n";
				return error;
			}
		}
		if(endDate<statringDate){
			error=errorEndDate+" must be greater than "+errorStartDate+"\n";
			return error;
		}
			
		if(curDate>endDate){
			error=errorEndDate+" must be greater than Todays date\n";
			return error;
		}	
			return error;
	}
	}

	function compareThreeDates(startDate, expirationDate, displayDate){

	if(startDate!=""&& expirationDate!=""&&displayDate!=""){	
		var error="";
		var statringDate=new Date(document.getElementById(startDate).value);
		var endDate=new Date(document.getElementById(expirationDate).value);
		var dispDate=new Date(document.getElementById(displayDate).value);
		var currentDate=new Date();
		var month = currentDate.getMonth()	
		var day = currentDate.getDate()
		var year = currentDate.getFullYear()
		var curDate=new Date(year,month,day);
		var typeCode = document.getElementById('operationType').value;

		if(typeCode != 'EditContent')
		{
			if(curDate>statringDate){
				error="Start Date must be greater than or equal to Todays date\n";
				return error;
			}
		}
		if(endDate<statringDate){
			error="Expiration date must be greater than Start Date\n";
			return error;
		}
		
			
		if(curDate>endDate){
			error="Expiration date must be greater than Todays date\n";
			return error;
		}
		
		if(dispDate<statringDate){
			error="Display date cannot be before the Start Date\n";
			return error;
		}

		/*if(curDate>dispDate){
			error="Display Date must be greater than or equal to Todays date\n";
			return error;
		}*/
			
		if(dispDate>endDate){
			error="Display date must be less than End date\n";
			return error;
		}


			return error;
	}
	}


	function assignErrorField(fieldName){

		

		if(fieldName=='title'){
			fieldName="Item Name";
		}
		if(fieldName=='displayName'){
			fieldName="Display Name";
		}

		if(fieldName=='displayDate'){
			fieldName="Display Date";
		}

		if(fieldName=='publicationName'){
			fieldName="Publication Name";
		}

		if(fieldName=='startDate'){
			fieldName="Start Date";
		}	
		
		if(fieldName=='expirationDate'){
			fieldName="Expiration Date";
		}

		if(fieldName=='author'){
			fieldName="Author";
		}

		if(fieldName=='par'){
			fieldName="PAR";
		}

		/*if(fieldName=='position'){
			fieldName="Position";
		}*/

		if(fieldName=='delayTime'){
			fieldName="Delay Time";
		}

		if(fieldName=='question'){
			fieldName="Question";
		}	
		
		if(fieldName=='answer'){
			fieldName="Answer";
		}

		if(fieldName=='author'){
			fieldName="Author";
		}

		if(fieldName=='htmlContent'){
			fieldName="Html Content";
		}

		if(fieldName=='url'){
			fieldName="URL";
		}

		if(fieldName=='contactName'){
			fieldName="Contact Name";
		}

		if(fieldName=='contactEmail'){
			fieldName="Contact Email";
		}

		if(fieldName=='contactPhone'){
			fieldName="Contact Phone";
		}

		if(fieldName=='meetingStartDate'){
			fieldName="Meeting Start Date";
		}

		if(fieldName=='meetingEndDate'){
			fieldName="Meeting End Date";
		}
		
		if(fieldName=='venue'){
			fieldName="Venue";
		}

		if(fieldName=='address1'){
			fieldName="Address1";
		}

		if(fieldName=='city'){
			fieldName="City";
		}
		
		if(fieldName=='state'){
			fieldName="State";
		}
		
		if(fieldName=='country'){
			fieldName="Country";
		}

		if(fieldName=='zip'){
			fieldName="Zip";
		}

		if(fieldName=='meetingwebsite'){
			fieldName="Meeting Website";
		}

		if(fieldName=='vendor'){
			fieldName="Vendor";
		}

		if(fieldName=='vendorUrl'){
			fieldName="URL";
		}

		if(fieldName=='programId'){
			fieldName="Program ID";
		}

		if(fieldName=='webCode'){
			fieldName="Web Conference Code";
		}

		if(fieldName=='webId'){
			fieldName="Web Conference ID";
		}

		if(fieldName=='conferencePassword'){
			fieldName="Password";
		}

		if(fieldName=='webUrl'){
			fieldName="URL";
		}

		if(fieldName=='welcomeMessage'){		
			fieldName="Welcome Message";
		}

		if(fieldName=='videoTop'){
			fieldName="Video Top";
		}

		if(fieldName=='videoBottom'){
			fieldName="Video Bottom";
		}

		if(fieldName=='sampleText'){
			fieldName="Sample Instruction Text";
		}

		if(fieldName=='materialText'){
			fieldName="Material Instruction Text";
		}
		if(fieldName=='faxTop'){
			fieldName="Fax Top";
		}

		if(fieldName=='faxBottom'){
			fieldName="Fax Bottom";
		}

		if(fieldName=='position'){
			fieldName="Position";
		}

		if(fieldName=='contactFax'){
			fieldName="Contact Fax";
		}
		if(fieldName=='uploadContent'){
			fieldName="Upload Item";
		}
		if(fieldName=='uploadImage'){
			fieldName="Upload Image";
		}
		if(fieldName=='uploadLogo'){
			fieldName="Program Logo";
		}
		if(fieldName=='uploadLogo1'){
			fieldName="Sample Logo";
		}
		if(fieldName=='uploadLogo2'){
			fieldName="Program Logo";
		}
		if(fieldName=='faqhtmlContent'){
			fieldName="Faq's Html Content";
		}
		return fieldName;

}
	function isValid(parm, val) {
		if (parm == "")
			return true;
		for (i = 0; i < parm.length; i++) {
			if (val.indexOf(parm.charAt(i), 0) == -1)
				return false;
		}
		return true;
	}
		function isValidColorCode(str) {
		var numb = '0123456789';
		var lwr = 'abcdefghijklmnopqrstuvwxyz';
		var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		var hexval = '#abcdefABCDEF';
		if (str != null) {
			var alphatest = isValid(str, lwr + upr);
			if (alphatest) {
				return true;
			} else {
				var siz = (str).length;
				if (siz == 4 || siz == 7) {
					if ((str).substring(0, 1) == "#") {
						var hexcheck = isValid(str,
								hexval + numb);
						if (hexcheck) { 
							return true;
						} else {
							alert("Enter Hexadecimal value\nExample:\nRed or #Ff0000");
							return false;
						}
					} else {
						alert("Hexadecimal value should start with #\nExample:\nRed or #Ff0000");
						return false;
					}
				} else {
					alert("Enter valid Hexadecimal value\nExample:\nRed or #Ff0000");
					return false;
				}
			}
		}
		return true;
	} 
	
	function validateDateField(startDateFieldId, endDateFieldId)
	{
		var str1  = document.getElementById(startDateFieldId).value;
		var str2  = document.getElementById(endDateFieldId).value;
		
		var month1 = Number(str1.substring (0, str1.indexOf ("/")));
		var date1 = str1.substring (str1.indexOf ("/")+1, str1.lastIndexOf ("/"));
		var year1 = str1.substring (str1.lastIndexOf ("/")+1, str1.length);

		var month2 = Number(str2.substring (0, str2.indexOf ("/")));
		var date2 = str2.substring (str2.indexOf ("/")+1, str2.lastIndexOf ("/"));
		var year2 = str2.substring (str2.lastIndexOf ("/")+1, str2.length);

		
		if (year1.length == 2){
			year1 = "20"+year1;
		} else if (year1.length == 1){
			year1 = "200"+year1;
		}
			
		if (year2.length == 2){
			year2 = "20"+year2;
		} else if (year2.length == 1){
			year2 = "200"+year2;
		}
		
		var currentDate=new Date();
		var startDate = new Date(year1, month1 - 1, date1);
		var endDate = new Date(year2, month2 - 1, date2);
		var today = new Date(currentDate.getFullYear(),currentDate.getMonth(),currentDate.getDate()); 

		if(startDate > endDate){
			return false;
		}
		return true;
	}

	function compareDate(dateFieldId)
	{
		var currentDate=new Date();
		var month = currentDate.getMonth();	
		var day = currentDate.getDate();
		var year = currentDate.getFullYear();
		var curDate=new Date(year,month,day);
	    var startingDate = document.getElementById(dateFieldId).value;
		if(startingDate > curDate){
			return false;
		}
		else
		{ return true; }
	}
	
	/**
	 * This function is used to get selected and sorted values in listbox 
	 * after entering values for cateogry,segments and brands in content.
	 * @param formname
	 * @param selname
	 * @param textname
	 * @return
	 */
	function SelObj(formname,selname,textname,str)
	{
		this.formname = formname;
		this.selname = selname;
		this.textname = textname;
		this.select_str = str || '';
		this.selectArr = new Array();
		this.initialize = initialize;
		this.bldInitial = bldInitial;
		this.bldUpdate = bldUpdate;
	}

	function initialize() 
	{
		if (this.select_str =='')
		{
			for(var i=0;i<document.forms[this.formname][this.selname].options.length;i++) 
			{
				this.selectArr[i] = document.forms[this.formname][this.selname].options[i];
				this.select_str += document.forms[this.formname][this.selname].options[i].value+":"+
				document.forms[this.formname][this.selname].options[i].text+",";
			}
		}
		else 
		{
			var tempArr = this.select_str.split(',');
			for(var i=0;i<tempArr.length;i++)
			{
				var prop = tempArr[i].split(':');
				this.selectArr[i] = new Option(prop[1],prop[0]);
		   }
		}
		return;
	}

	function bldInitial() 
	{
		this.initialize();
		for(var i=0;i<this.selectArr.length;i++)
		document.forms[this.formname][this.selname].options[i] = this.selectArr[i];
		document.forms[this.formname][this.selname].options.length = this.selectArr.length;
		return;
	}

	function bldUpdate()
	{
		var str = document.forms[this.formname][this.textname].value.replace('^\\s*','');
		if(str == '') {this.bldInitial();return;}
		this.initialize();
		var j = 0;
		pattern1 = new RegExp("^"+str,"i");
		for(var i=0;i<this.selectArr.length;i++)
		if(pattern1.test(this.selectArr[i].text))
		document.forms[this.formname][this.selname].options[j++] = this.selectArr[i];
		document.forms[this.formname][this.selname].options.length = j;
		if(j==1)
		{
			document.forms[this.formname][this.selname].options[0].selected = true;
		}
	}

	function setUp(pageid)
	{
		if(pageid != '5')
		{
			obj1 = new SelObj('createContent','categoriesList','cateogryString');
			obj1.bldInitial();
		}
		obj2 = new SelObj('createContent','segmentList','segmentString');
		obj2.bldInitial();
		obj3 = new SelObj('createContent','brandList','brandString');
		obj3.bldInitial();
		if(pageid == '1' || pageid == '2' || pageid == '4')
		{
			obj4 = new SelObj('createContent','conditionList','conditionString');
			obj4.bldInitial();
		}
		if(pageid == '9')
		{
			obj4 = new SelObj('createContent','treatmentList','treatmentString');
			obj4.bldInitial();
		}
	}
	
	/**
	 * Function to validate Email Id
	 * @param sText
	 * @return
	 */
	function isValidEmail(sText) {
        var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
        return reEmail.test(sText);
    }
	/**
	 * Function to erase the value
	 * of text boxes.
	 * @param elemId
	 * @return
	 */
	function eraseValue(elemId)
	{
	    var emailValue = Trim(document.getElementById(elemId).value);
	    if(emailValue != null)
	    {
	    	if(emailValue == "Enter Email Address" 
	    		|| emailValue == "New Email Address"
	    			|| emailValue == "Confirm New Email Address")
	        document.getElementById(elemId).value = "";
	    }
	}
	/**
	 * This function is used to upload the file for content pages.
	 * @param url
	 * @return
	 */
	function uploadPopup(url)
	{
		popupWindow = window.open("", "ContentUpload", "directories=no,toolbar=no,menubar=no,scrollbars=yes,resizable=no,height=340,width=570");
		document.frmUpload.action=url;
		document.frmUpload.target="ContentUpload";
		if (popupWindow.opener == null) 
			 popupWindow.opener = self;
	   	document.frmUpload.submit();
		return;
	}
	
	function uploadPopupForLogo1(url)
	{
		popupWindow = window.open("", "ProductPicture1UploadPopup", "directories=no,toolbar=no,menubar=no,scrollbars=yes,resizable=no,height=340,width=570");
		document.frmUpload.action=url;
		document.frmUpload.target="ProductPicture1UploadPopup";
		document.frmUpload.submit();
		return;
	}

	function uploadPopupForLogo2(url)
	{
		popupWindow = window.open("", "ProductPicture2UploadPopup", "directories=no,toolbar=no,menubar=no,scrollbars=yes,resizable=no,height=340,width=570");
		document.frmUpload.action=url;
		document.frmUpload.target="ProductPicture2UploadPopup";
		document.frmUpload.submit();
		return;
	}
	
	function imgUpload(){

	}

	function setURL(op, val, size)
	{
		if(op == "ContentUpload")
		{
			this.document.createContent.uploadContent.value = val;
			this.document.createContent.size.value=size;
		}
		else if(op == "ProductPicture1Upload")
		{
			this.document.createContent.uploadLogo1.value = val;
		}
		else if(op == "ProductPicture2Upload")
		{
			this.document.createContent.uploadLogo2.value = val;
		}
	}
	/**
	 * Function to limit the text area.
	 * It will take id of input element and limit size.
	 * @param limitField
	 * @param limitNum
	 * @return
	 */
	function limitText(limitField, limitNum) {
	    if (limitField.value.length > limitNum) {
	        limitField.value = limitField.value.substring(0, limitNum);
	    } 
	}
	/**
	 * This Function is used to Check the date format in MM/DD/YYYY
	 */
	var dtCh= "/";
	var minYear=1900;
	var maxYear=2100;

	function isInteger(s){
		var i;
	    for (i = 0; i < s.length; i++){   
	        // Check that current character is number.
	        var c = s.charAt(i);
	        if (((c < "0") || (c > "9"))) return false;
	    }
	    // All characters are numbers.
	    return true;
	}

	function stripCharsInBag(s, bag){
		var i;
	    var returnString = "";
	    // Search through string's characters one by one.
	    // If character is not in bag, append to returnString.
	    for (i = 0; i < s.length; i++){   
	        var c = s.charAt(i);
	        if (bag.indexOf(c) == -1) returnString += c;
	    }
	    return returnString;
	}

	function daysInFebruary (year){
		// February has 29 days in any year evenly divisible by four,
	    // EXCEPT for centurial years which are not also divisible by 400.
	    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
	}
	function DaysArray(n) {
		for (var i = 1; i <= n; i++) {
			this[i] = 31
			if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
			if (i==2) {this[i] = 29}
	   } 
	   return this
	}

	function isDateCheck(dtStrValue){
		var dtStr=document.getElementById(dtStrValue).value;
		var errorMessage="";
		var daysInMonth = DaysArray(12);
		var pos1=dtStr.indexOf(dtCh);
		var pos2=dtStr.indexOf(dtCh,pos1+1);
		var strMonth=dtStr.substring(0,pos1);
		var strDay=dtStr.substring(pos1+1,pos2);
		var strYear=dtStr.substring(pos2+1);
		
		strYr=strYear
		if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
		if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
		for (var i = 1; i <= 3; i++) {
			if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
		}
		month=parseInt(strMonth)
		day=parseInt(strDay)
		year=parseInt(strYr)
		if(dtStr !=""){
			if (pos1==-1 || pos2==-1){
				errorName=assignErrorField(dtStr);
				return errorMessage +="The field " +errorName + " format should be MM/DD/YYYY\n";
				document.getElementById(dtStr).focus();
			}
			if (strMonth.length<1 || month<1 || month>12){
				errorName=assignErrorField(dtStr);
				return errorMessage +="Please enter a valid month\n";
				document.getElementById(dtStr).focus(); 
			}
			if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
				errorName=assignErrorField(dtStr);
				return errorMessage +="Please enter a valid day\n";
				document.getElementById(dtStr).focus(); 
			}
			if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
				errorName=assignErrorField(dtStr);
				return errorMessage +="Please enter a valid 4 digit year between "+minYear+" and "+maxYear+"\n";
				document.getElementById(dtStr).focus(); 
			}
			if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
				errorName=assignErrorField(dtStr);
				return errorMessage +="Please enter a valid date\n";
				document.getElementById(dtStr).focus(); 
			}
		}
	return errorMessage
	}
	/**
	*Function to to validate email format
	*@param formId 
	*@param element-id or element-name
	*/
    function validateEmail(email){
		var errorMessage ="";
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	    var email1 =document.getElementById(email).value;
	    if(email1 != null && email1 != "" && reg.test(email1) == false){
			errorName=assignErrorField(email);
			return errorMessage += "The field " +errorName + " contains Invalid Email Address\n";
			document.getElementById(email).focus();
	    }else
		{
			return errorMessage;
		}
    }
    /**
	*Function to to validate the feild which is combination of alphabet and number only
	*@param formId 
	*@param element-id or element-name
	*/
    function validateParNumber(fieldName){
    	var errorMessage ="";
    	var parNumber = document.getElementById(fieldName).value;
		if(parNumber != null && parNumber != '') {
			if (parNumber.match(/^[0-9\s]+$/) ) {
				return errorMessage += "You must enter alpha numeric value for PAR\n";
				document.getElementById(fieldName).focus();
			}	else if(parNumber.match(/^[a-zA-Z\s]+$/)) {
				return errorMessage += "You must enter alpha numeric value for PAR\n";
				document.getElementById(fieldName).focus();
			} 	 
			//Start - Change to accept special character comma - removing "," from badChar string; 
			var badChar = " @/\\+()*&^%$#?<>=!~`[]|:;'-_.";
			//End - Change to accept special character comma - removing "," from badChar string; 
			for (j=0;j<badChar.length;j++) {
				var illChar = badChar.charAt(j);
				if (parNumber.indexOf(illChar,0) !=-1){
					return errorMessage += "You must enter alpha numeric value for PAR\n";
					document.getElementById(fieldName).focus();
					}
				}
		}
		return errorMessage;
    }
    /**
     * method checks the duplicate4 brand name and alerts the user.
     * @return
     */
    function CheckForDuplicateBrandName()
    {
    	var isBrandNameExists = document.brandForm.brandNameExists.value;
    	var isBrandTitleExists = document.brandForm.brandTitleExists.value;
    	if(isBrandNameExists == "true")
    	{
    		alert('Brand Name already exists. Please enter any other brand name ');
    		return false;
    	}
    	if(isBrandTitleExists == "true")
    	{
    		alert('Brand Title should be unique. Please enter any other brand title ');
    		return false;
    	}
    }
    /**]
     * method validate the brand form.
     * @return
     */
    function submitBrandForm()
    {
    	//var isBrandNameExists = CheckForDuplicateBrandName();
    	var flag2;
    	if(Trim(document.brandForm.brandName.value)=="")
    	{
    		alert('Enter a Brand Name.');
    		document.brandForm.brandName.focus();
    		return false;
    	}
    	if(Trim(document.brandForm.brandTitle.value)=="")
    	{
    		alert('Enter Brand Title.');
    		document.brandForm.brandTitle.focus();
    		return false;
    	}
    	if(validateTextBox('brandTitle', 'alphanumeric')==false)
		{
			alert('Brand title cannot contain special charecters.');
			this.document.brandForm.brandTitle.focus();
            return false;
		}
    	if(Trim(document.brandForm.labelId.value)=="")
    	{
    		alert('Enter FDA Label ID.');
    		document.brandForm.labelId.focus();
    		return false;
    	}
    	/*else if(!validateTextBox('labelId','alphanumeric'))
    	{
    		alert('Label Id should be alphanumeric value');
    		document.brandForm.labelId.focus();
    		return false;
    	}*/
    	if(Trim(document.brandForm.condition.value)=="" || checkComboBoxSelection("condition")==false)
    	{
    		alert('Select atleast one Condition.');
    		document.brandForm.condition.focus();
    		return false;
    	}
    	if(document.brandForm.productType[0].checked==false && document.brandForm.productType[1].checked==false)
    	{
    		alert('Select one Product Type.');
    		return false;
    	}
    	if(isMaxLengthExceeds('productShortDescription',400))
    	{
    		alert('Product Short Description cannot be more than 400 Chars');
    		document.brandForm.productShortDescription.focus();
    		return false;
    	}
		//Added as part of Release 3.3 changes
		if(isMaxLengthExceeds('brandPageDescription',400))
    	{
    		alert('Brand Page Description cannot be more than 400 Chars');
    		document.brandForm.brandPageDescription.focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('genericNames',400))
    	{
    		alert('Generic Names for Brands cannot be more than 400 Chars');
    		document.brandForm.genericNames.focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('fairBalanceUrl',2000))
    	{
    		alert('Fair Balance HTML text cannot be more than 2000 Chars');
    		document.brandForm.fairBalanceUrl.focus();
    		return false;
    	}
    	// Start: Added for PI CR
    	/*white_space(document.brandForm.blackBoxWarning);
    	if(Trim(document.brandForm.blackBoxWarning.value)=="")
    	{
    		alert('Enter Safety Information HTML Text');
    		document.brandForm.blackBoxWarning.focus();
    		return false;
    	}*/
    	// End : Added for PI CR
    	if(isMaxLengthExceeds('blackBoxWarning',22000))
    	{
    		alert('Safety Information - Footer Section cannot exceed 22,000 Chars');
    		document.brandForm.blackBoxWarning.focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('safetyInfoContent',22000))
		{
			alert('Safety Information - Content Section cannot exceed 22,000 Chars');
			document.brandForm.safetyInfoContent.focus();
			return false;
		}
    	/*if(Trim(document.brandForm.brandUrl.value) != "" && validateURL('brandUrl'))
    	{
    		alert('Please enter a valid Product Website 1 like http://www.abc.com');
    		document.brandForm.brandUrl.focus();
    		return false;
    	}
    	if(Trim(document.brandForm.unbrandedUrl.value) != "" && validateURL('unbrandedUrl'))
    	{
    		alert('Please enter a valid Product Website 2 like http://www.abc.com');
    		document.brandForm.unbrandedUrl.focus();
    		return false;
    	}
    	if(Trim(document.brandForm.productWebSite3.value) != "" && validateURL('productWebSite3'))
    	{
    		alert('Please enter a valid Product Website 3 like http://www.abc.com');
    		document.brandForm.productWebSite3.focus();
    		return false;
    	}
    	if(Trim(document.brandForm.productWebSite4.value) != "" && validateURL('productWebSite4'))
    	{
    		alert('Please enter a valid Product Website 4 like http://www.abc.com');
    		document.brandForm.productWebSite4.focus();
    		return false;
    	}
    	if(Trim(document.brandForm.Pdf.value) != "" && validateURL('Pdf'))
        {
            alert('Please enter a valid PI Pdf 1 link like http://www.abc.com');
            document.brandForm.Pdf.focus();
            return false;
        }
        if(Trim(document.brandForm.Pdf2.value) != "" && validateURL('Pdf2'))
        {
            alert('Please enter a valid PI Pdf 2 link like http://www.abc.com');
            document.brandForm.Pdf2.focus();
            return false;
        }
        */
    	if(isMaxLengthExceeds('preTabHtml',30000))
    	{
    		alert('Pre Tab HTML value cannot be more than 30,000 Chars');
    		document.brandForm.preTabHtml.focus();
    		return false;
    	}
    	
    	if(isMaxLengthExceeds('tab1Html',30000))
    	{
    		alert('Tab 1 HTML value cannot be more than 30,000 Chars');
    		document.brandForm.tab1Html.focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('tab2Html',30000))
    	{
    		alert('Tab 2 HTML value cannot be more than 30,000 Chars');
    		document.brandForm.tab2Html.focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('tab3Html',30000))
    	{
    		alert('Tab 3 HTML value cannot be more than 30,000 Chars');
    		document.brandForm.tab3Html.focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('tab4Html',30000))
    	{
    		alert('Tab 4 HTML value cannot be more than 30,000 Chars');
    		document.brandForm.tab4Html.focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('tab5Html',30000))
    	{
    		alert('Tab 5 HTML value cannot be more than 30,000 Chars');
    		document.brandForm.tab5Html.focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('postTabHtml',4000))
    	{
    		alert('Post Tab HTML value cannot be more than 4000 Chars');
    		document.brandForm.postTabHtml.focus();
    		return false;
    	}
    	document.brandForm.encoding="multipart/form-data";
    	document.brandForm.submit();
    }
    /**
     * function to validate and submit the portfolio form.
     * @return
     */
    function submitPortfolioForm() {
    	if(Trim(document.portfolioForm.portfolioName.value)=="")
    	{
    		alert('Enter a Portfolio Name.');
    		document.portfolioForm.portfolioName.focus();
    		return false;
    	}
    	if(Trim(document.portfolioForm.portfolioTitle.value)=="")
    	{
    		alert('Enter Portfolio Title.');
    		document.portfolioForm.portfolioTitle.focus();
    		return false;
    	}
    	if(validateTextBox('portfolioTitle', 'alphanumeric')==false)
    	{
    		alert('Portfolio title cannot contain special charecters.');
    		this.document.portfolioForm.portfolioTitle.focus();
            return false;
    	}
    	if(isMaxLengthExceeds('portfolioShortDescription',400))
    	{
    		alert('Portfolio Short Description cannot be more than 400 Chars');
    		document.getElementById('portfolioShortDescription').focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('genericNames',400))
    	{
    		alert('Generic Names for Portfolios cannot be more than 400 Chars');
    		document.getElementById('genericNames').focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('blackBoxWarning',22000))
    	{
    		alert('Safety Information - Footer Section cannot exceed 22,000 Chars');
    		document.getElementById('blackBoxWarning').focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('preTabHtml',20000))
    	{
    		alert('Pre Tab HTML value cannot be more than 20,000 Chars');
    		document.getElementById('preTabHtml').focus();
    		return false;
    	}
    	
    	if(isMaxLengthExceeds('tab1Html',30000))
    	{
    		alert('Tab 1 HTML value cannot be more than 30,000 Chars');
    		document.getElementById('tab1Html').focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('tab2Html',30000))
    	{
    		alert('Tab 2 HTML value cannot be more than 30,000 Chars');
    		document.getElementById('tab2Html').focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('tab3Html',30000))
    	{
    		alert('Tab 3 HTML value cannot be more than 30,000 Chars');
    		document.getElementById('tab3Html').focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('tab4Html',30000))
    	{
    		alert('Tab 4 HTML value cannot be more than 30,000 Chars');
    		document.getElementById('tab4Html').focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('tab5Html',30000))
    	{
    		alert('Tab 5 HTML value cannot be more than 30,000 Chars');
    		document.getElementById('tab5Html').focus();
    		return false;
    	}
    	if(isMaxLengthExceeds('postTabHtml',4000))
    	{
    		alert('Post Tab HTML value cannot be more than 4000 Chars');
    		document.getElementById('postTabHtml').focus();
    		return false;
    	}
    	document.portfolioForm.submit();
    }
