/*** This JavaScript file is to validate HTML configs ***/

/********* Configurable SECTION Start *********/

//If login check is required
var checkLogin = false;

//If mimimum age check is required
var checkAge = false;

//Minimum age required to submit this form
var minAge = 18;

//Alert Messages for age & login check
var ageChkMsg = "You must be " + minAge + " years of age to submit this form.";
var loginChkMsg = "Please login to submit your request.";


//If there r 3 textboxes to enter a Phone Number, 1 for area code & 2 for the number
var mergePhoneNum = false;

//If there r 2 textboxes to enter Street Address 1 and 2
var mergeStreetAdd = false;


var fnameChkReqd = false;
var fnameChkMsg = "Please enter your First Name.";

var lnameChkReqd = false;
var lnameChkMsg = "Please enter your Last Name.";

var streetAddChkReqd = false;
var streetAddChkMsg = "Please enter your Street Address.";

var cityChkReqd = false;
var cityChkMsg = "Please enter your City.";

var stateChkReqd = false;
var stateChkMsg = "Please select your State.";

var zipChkReqd = false;
var zipChkMsg = "Please enter a valid Zip Code.";

var emailChkReqd = false;
var emailChkMsg = "Please enter a valid EMail Address.";

var pnumberChkReqd = false;
var pnumberChkMsg = "Please enter a valid Phone Number.";

var bdateChkReqd = false;
var bdateChkMsg = "Please enter a valid Date of Birth.";

var myspaceUrlChkReqd = false;
var myspaceUrlChkMsg = "Please enter your MySpace URL.";

var bandNameChkReqd = false;
var bandNameChkMsg = "Please enter your Band Name.";

var songNameChkReqd = false;
var songNameChkMsg = "Please enter the Song Name.";

var commentChkReqd = false;
var commentChkMsg = "Please enter the Comments.";

var uploadFileChkReqd = false;
var uploadFileChkMsg = "Please select a file to upload.";

var termsChkReqd = false;
var termsChkMsg = "Please confirm that you have read, understood, and agree to the terms and conditions.";

/********* Configurable SECTION End *********/


//Get isLoggedIn from QueryString of the current URL (if this form was opened in a new window OR iFrame)
var isLoggedIn;
if (location.search.length > 0)
isLoggedIn = unescape(location.search.substring(1))

/***  Start
//For opening in new window (put following code):
window.open("video_form.html?" + isLoggedIn);

//For opening in an iframe (put following code):
var iFrameNew = document.getElementById("iFrameNew");
iFrameNew.src = "video_form.html?" + isLoggedIn;
iFrameNew.reload(true);
End  ***/


/*****************************************************************************
SubmitForm: This function submits the form to the fuseaction given in form action property. 
- Checks for minimum age if required to submit this form.
- Validates the form fields.
- If phone number was entered in 3 different fields, then merges the phonenumber in 1 hidden field.
- If there is any media being uploaded from the form, sets the value of the field filename.
Returns: false if mimimum age is not met/user is not logged in/validation fails;
*****************************************************************************/
function SubmitForm()
{
    if (CheckLogin())
    {
        //If minimum age check is required
        if (CheckAge() == false)
        {
            window.alert(ageChkMsg);
            return false;
        }
        
    	var f = GetForm();
        if (Validated())
        {
            //If there r 3 textboxes to enter a Phone Number, 1 for area code & 2 for the number
            if (mergePhoneNum == true)
                PhoneNumberMerge();
            f.submit();
        }
    }
    else
    {
        alert(loginChkMsg);
        return false;
    }
}

/*****************************************************************************
GetForm: This function gets the form named 'aspnetForm'.
*****************************************************************************/
function GetForm()
{
    var theForm = document.forms['aspnetForm'];
    if (!theForm)theForm = document.aspnetForm;
    return theForm;
}

/*****************************************************************************
CheckLogin: This function checks if the user is logged into MySpace.
    - The variable isLoggedIn is set to a non-zero value once a user logs into www.MySpace.com
Returns: false if user is not logged in; otherwise true;
*****************************************************************************/
function CheckLogin()
{
    if (checkLogin == false)
        return true;
        
	if (typeof isLoggedIn == "undefined" || isLoggedIn < 1)
   		return false;
    else
	    return true;
}

/*****************************************************************************
CheckAge: This function checks the minimum age of user logged into MySpace.
- The variable age is set to a non-zero value once a user logs into www.MySpace.com
Returns: false if user does not meet the minimum age; otherwise true;
*****************************************************************************/
function CheckAge() {
    if (checkAge == false)
        return true;

    if (typeof age == "undefined" || age < minAge)
        return false;
    else
        return true;
}

/*****************************************************************************
Validated: This function validates all fields in this form.
Returns: false if validation fails; otherwise true;
*****************************************************************************/
function Validated()
{
   var theForm = GetForm();
    
    //Validation for First Name
    if (fnameChkReqd == true) 
    {
        if (IsEmpty('fname') == true) 
        {
            alert(fnameChkMsg);
            document.getElementById('fname').focus();
            return false;
        }
    }
   //Validation for Last Name
    if (lnameChkReqd == true) 
    {
        if (IsEmpty('lname') == true) 
        {
            alert(lnameChkMsg);
            document.getElementById('lname').focus();
            return false;
        }
    }

    //Validation for Street Address
    if (streetAddChkReqd == true) 
    {
        if (mergeStreetAdd == false) 
        {
            if (IsEmpty('streetAddress') == true) 
            {
                alert(streetAddChkMsg);
                document.getElementById('streetAddress').focus();
                return false;
            }
        }
        else 
        {
            //OR if there r 2 textboxes for Street Address 1 & 2, then concatenate the 2 in streetAddress
            if (IsEmpty('address1') == true) 
            {
                alert(streetAddChkMsg);
                document.getElementById('address1').focus();
                return false;
            }
            else 
            {
                if (document.getElementById('address2').value.length < 1 || hasWhiteSpace(document.getElementById('address2').value)) 
                    theForm.streetAddress.value = theForm.address1.value;
                else 
                    theForm.streetAddress.value = (theForm.address1.value + ',' + theForm.address2.value);
            }
        }
    }
    
   //Validation for City
    if (cityChkReqd == true) 
    {
        if (IsEmpty('city')) 
        {
            alert(cityChkMsg);
            document.getElementById('city').focus();
            return false;
        }
    }
   //Validation for State
    if (stateChkReqd == true) 
    {
        if (IsEmpty('state')) 
        {
            alert(stateChkMsg);
            document.getElementById('state').focus();
            return false;
        }
    }
   //Validation for Zip code
    if (zipChkReqd == true) 
    {
        if (IsEmpty('zip') || !IsInteger(document.getElementById('zip').value)) 
        {
            alert(zipChkMsg);
            document.getElementById('zip').focus();
            return false;
        }
    }

   //Validation for EMail
    if (emailChkReqd == true) 
    {
        if (IsEmpty('email') == true || IsInvalidEmail(document.getElementById('email').value)) 
        {
            alert(emailChkMsg);
            document.getElementById('email').focus();
            return false;
        }
    }
    
   //Validation for Phone Number
    if (pnumberChkReqd == true) 
    {
        if (IsEmpty('pnumber') == true || IsInvalidPhone(document.getElementById('pnumber').value)) 
        {
            alert(pnumberChkMsg);
            document.getElementById('pnumber').focus();
            return false;
        }
    }

   //Validation for Date of Birth
    if (bdateChkReqd == true) 
    {
        if (IsEmpty('bdate') == true || IsInvalidDate(document.getElementById('bdate'))) 
        {
            alert(bdateChkMsg);
            document.getElementById('bdate').focus();
            return false;
        }
    }

    //Validation for Band Name
    if (bandNameChkReqd == true) {
        if (IsEmpty('bandName') == true) {
            alert(bandNameChkMsg);
            document.getElementById('bandName').focus();
            return false;
        }
    }

    //Validation for Song Name
    if (songNameChkReqd == true) 
    {
        if (IsEmpty('songName') == true) 
        {
            alert(songNameChkMsg);
            document.getElementById('songName').focus();
            return false;
        }
    }

    //Validation for MySpace URL
    if (myspaceUrlChkReqd == true) 
    {
        if (IsInvalidMySpaceUrl(document.getElementById('bandurl').value)) 
        {
            alert(myspaceUrlChkMsg);
            document.getElementById('bandurl').focus();
            return false;
        }
    }

    //Validation for Comments
    if (commentChkReqd == true) 
    {
        if (IsEmpty('comment') == true) 
        {
            alert(commentChkMsg);
            document.getElementById('comment').focus();
            return false;
        }
    }

    //Validation for Media File Upload
    if (uploadFileChkReqd == true) 
    {
        if (document.getElementById('uploadFile').value.length < 1) 
        {
            alert(uploadFileChkMsg);
            document.getElementById('uploadFile').focus();
            return false;
        }
        if (!ExtensionValidator('uploadFile')) 
        {
            if (!LongExtensionCheck()) 
            {
                document.getElementById('uploadFile').focus();
                return false;
            }
        }
    }

    //Validation for terms & conditions
    if (termsChkReqd == true) 
    {
        if (document.getElementById('terms').checked == false)  
        {
            alert(termsChkMsg);
            return false;
        }
    }

    return true;
}

/*****************************************************************************
IsEmpty: This function validates if the text in the input control is empty.
Argument: Control to be validated 
Returns: true if data entered has 
   - A length < 1 or
   - Has whitespace
*****************************************************************************/
function IsEmpty(controlName) 
{
    if (document.getElementById(controlName).value.length < 1 || hasWhiteSpace(document.getElementById(controlName).value))
        return true;
    return false;
}

/*****************************************************************************
IsInvalidPhone: This function checks if the input string has a valid phone number.
Argument: String to be validated 
    An invalid phone number has either of the following:
    - A length not equal to 10 
    - Has chars other than “0123456789 ()-“ 
Returns: true if it has an invalid phone number; false otherwise;
*****************************************************************************/
function IsInvalidPhone(p)
{
	if(p.length != 1) return true;
	for(i=0;i<p.length;i++) if(IsInvalidChar(p.charAt(i))) return true;
	return false;
}

/*****************************************************************************
IsInvalidChar: This function checks if the input string has an invalid character.
Argument: Character to be validated 
    -An invalid character has chars other than “0123456789 ()-“ 
Returns: true if it has an invalid character; false otherwise;
*****************************************************************************/
function IsInvalidChar(c)
{
	var vC = "0123456789 ()-";
	if(vC.indexOf(c)<0){return true};
	return false;
}

/*****************************************************************************
IsInvalidEmail: Checks if the input string has an invalid email address.
Argument: String to be validated 
Returns: true if invalid; false otherwise.
*****************************************************************************/
function IsInvalidEmail(strng) {
    var emailFilter = /^.+@.+\..{2,3}$/;
    if (strng < 1)
        return true;

    if (!(emailFilter.test(strng)))
        return true;
    else {
        //test email for illegal characters
        var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/
        if (strng.match(illegalChars))
            return true;
    }
    return false;
}

/*****************************************************************************
IsInvalidMySpaceUrl: Checks if the input string has an invalid MySpace URL.
Argument: String to be validated 
- A length of less than 1 
- A regular expression pattern that matches http://myspace.com/xyz or http://www.myspace.com/xyz 
or www.myspace.com/xyz or myspace.com/xyz.
Returns: true if invalid; false otherwise.
*****************************************************************************/
function IsInvalidMySpaceUrl(url) 
{
    if (url.length < 1) return true;
    var pattern = '^(http://myspace[.]com|http://www[.]myspace[.]com|www[.]myspace[.]com|myspace[.]com)/[_a-zA-Z0-9-]';
    if (validateValue(url, pattern) == false)
        return true;
    return false;
}

/*****************************************************************************
IsInteger: Checks if the input string has only digits.
Argument: String to be validated 
Returns: true if it is an integer; false otherwise.
*****************************************************************************/
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;
}

/*****************************************************************************
hasWhiteSpace: This function checks if the input string has any whitespace.
Argument: String to be validated 
Returns: true if it has whitespace; false otherwise;
*****************************************************************************/
function hasWhiteSpace(s) 
{
    reWhiteSpace = new RegExp(/^\s+$/);

    // Check for white space
    if (reWhiteSpace.test(s))
        return true;

    return false;
}

/*****************************************************************************
PhoneNumberMerge: This function concatenates the Phone number entered in 3 textboxes
    -Concatenates the values of pnumber1, pnumber2 and pnumber3 in pnumber.
*****************************************************************************/
function PhoneNumberMerge()
{
    var p1 = document.getElementById('pnumber1').value;
    var p2 = document.getElementById('pnumber2').value;	
    var p3 = document.getElementById('pnumber3').value;	
	
    var pTotal = '('+p1+') '+ p2+'-'+p3;
    document.getElementById("pnumber").value = pTotal;
}

/*****************************************************************************
validateValue: Validates that a string matches a valid regular expression value.
Arguments: 
  -strValue : String to be tested for validity
  -strMatchPattern : String containing a valid regular expression match pattern.
Returns: true if valid; false otherwise.
*****************************************************************************/
function validateValue( strValue, strMatchPattern ) 
{
    var objRegExp = new RegExp( strMatchPattern);

     //check if string matches pattern
     return objRegExp.test(strValue);
}

/*****************************************************************************
IsInvalidDate: Checks if the input string has an invalid date.
Argument: String to be validated
   This function uses following helper functions: 
      -isDate 
      -daysInFebruary 
      -DaysArray 
      -stripCharsInBag 
Returns: true if it has an invalid date; false otherwise.
*****************************************************************************/
function IsInvalidDate(bdate)
{
    var dtStr = new Date;
    dtStr = bdate.value;

    if (isDate(dtStr, bdate)==false)
    {
        return true;
    }
     return false;
 }	
function isDate(dtStr, bdate)
{
	var dtCh= "/";
	var minYear=1900;
	var maxYear=2100; 
	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 (pos1==-1 || pos2==-1)
	{
		 alert("The date format should be : mm/dd/yyyy")
		 //document.getElementById(fieldName).focus();
		 bdate.focus();
		 return false;
	}
	if (strMonth.length<1 || month<1 || month>12)
	{
		alert("Please enter a valid month")
		//document.getElementById(fieldName).focus();
		 bdate.focus();
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
	{
	   alert("Please enter a valid day");
	   //document.getElementById(fieldName).focus();
		 bdate.focus();
	   return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear)
	{
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		//document.getElementById(fieldName).focus();
		 bdate.focus();
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || IsInteger(stripCharsInBag(dtStr, dtCh))==false)
	{
		  alert("Please enter a valid date");
		  //document.getElementById(fieldName).focus();
		 bdate.focus();
		  return false;
	}
	return true;
}
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 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;
}

/*****************************************************************************
CheckFieldLength: Checks the length of the data entered by the user in a control like textarea.
Arguments: 
  - Control to be checked for length. 
  - Name of the control that contains the character count. 
  - Name of the control that contains the remaining character count. 
  - Maximum char’s that can be entered by the user. 
Ex:       
<textarea class="commentBox" name="comment" id="comment" cols="15" style="overflow:auto;" rows="10" 
onmouseout="CheckFieldLength(comment, 'charcount', 'remaining', 250);" 
onkeydown="CheckFieldLength(comment, 'charcount', 'remaining', 250);" 
onkeyup="CheckFieldLength(comment, 'charcount', 'remaining', 250);"></textarea>
<label class="maxtext">
  <span id="charcount">0</span> chars. entered | <span id="remaining">250</span> chars. remaining
</label>
*****************************************************************************/
function CheckFieldLength(fn, wn, rn, mc) 
{
      var len = fn.value.length;
      if (len > mc) 
      {
        fn.value = fn.value.substring(0,mc);
        len = mc;
      }
      document.getElementById(wn).innerHTML = len;
      document.getElementById(rn).innerHTML = mc - len;
}

/************************* Media File Upload section START **************************/


/*****************************************************************************
makeText: Sets value of hidden field filename to a unique name.
  - Calls function S4() which creates the file name using random numbers
*****************************************************************************/
function makeText()
{
    //alert(S4() + "-" + S4());
    document.getElementById("filename").value = S4() + "-" + S4();
}
function S4() {
    var rndNum = Math.floor((Math.random()) * 10000);

    if (rndNum > 999)
        return rndNum;
    else if (rndNum > 99)
        return "0" + rndNum
    else if (rndNum > 9)
        return "00" + rndNum
    else
        return "000" + rndNum
}

/*****************************************************************************
ExtensionValidator: Checks if the uploaded file has one of the 3 character accepted extensions.
Argument: Upload file control to be validated with the name/id ‘uploadFile’ 
  - This function sets all accepted extensions in variable ext3. It only checks for 3 character extensions. 
  - If the extension is valid, it also sets the hidden field ‘filetype’ to this extension. 
Returns: True if it has a valid extension; false otherwise
*****************************************************************************/
function ExtensionValidator(idName)
{
	var fileName = document.getElementById(idName).value;
	var extension = fileName.substring(fileName.length-3,fileName.length);
	var extension2 = fileName.substring(fileName.length-4, fileName.length);
			
	var ext3 = extension.toLowerCase();
	var ext4 = extension2.toLowerCase()

	if(ext3 == 'mp3' || ext3 == 'avi' || ext3 == 'wav' || ext3 == 'aac' || ext3 == 'aif' || ext3== 'iff' || ext3 == 'm3u' || ext3 =='mid' || ext3 =='mpa' || ext3 =='wma' || ext3 =='ram' || ext3 =='.ra')
	{
		document.getElementById('filetype').value = ext3;
		return true;
	}	
	else
	{
		return false;
	}
}

/*****************************************************************************
LongExtensionCheck: Checks if the uploaded file has one of the 4 character accepted extensions from
  the control ‘uploadFile’.
- This function sets all accepted extensions in variable ext4. It only checks for 4 character extensions. 
- If the extension is valid, it also sets the hidden field ‘filetype’ to this extension. 
Returns: True if it has a valid extension; false otherwise
*****************************************************************************/
function LongExtensionCheck()
{
	var fileName = document.getElementById('uploadFile').value;
	var extension2 = fileName.substring(fileName.length-4, fileName.length);
	var ext4 = extension2.toLowerCase()

	if (ext4 == 'mpeg' || ext4 == 'midi')
	{
		document.getElementById('filetype').value = ext4;
		return true;
	}
	else
	{
		alert('Unacceptable file type.  Please select a different audio file to submit.');
		return false;
	}
	return false;
}

/*****************************************************************************
ClearValue: Clears the value of control of type file, named 'uploadFile'.
*****************************************************************************/
function ClearValue()
{
	alert('Please use the browse button to locate and select the audio file you would like to upload'); 	
	document.getElementById('uploadFile').value="";
}

/************************** Media File Upload section END ***************************/
