var gIsIE = document.all;
var gIsIE7 = false;
var gIsProcessing = false;
var gMaxImageSizeLimit = 2560000;	
window.onerror=silentHandler;

function silentHandler()  {return true;}

// This function sets the processing variable that tells the system rather or
// not to allow the user to re-submit the page or not.
function setProcessing(isProcessing, btnUpload)
{		
	gIsProcessing = isProcessing;
	gIsIE7 = (typeof document.body.style.maxHeight != "undefined");
	
	if(isProcessing) showMessage("<center><br><br><b>Loading....Please Wait.</b><br><br><img src='http://www.istaintware.net/storage/images/loading.gif'></center>");
	else hideMessage();		
	
	if(btnUpload!=null) 
	{
		var oBtn = document.getElementById(btnUpload)
		if(oBtn!=null) oBtn.disabled = isProcessing;
	}
}

// This function displays a message to the user within a rectangular box in the middle of the screen
function showMessage(txt)
{
	var oDiv = document.getElementById("msgDiv");
	if(oDiv)
	{
		oDiv.innerHTML = txt;
		oDiv.style.visibility = "visible";
	}
}

// This function hides the notify message shown to the user .
function hideMessage()
{
	var oDiv = document.getElementById("msgDiv");
	if(oDiv)
	{
		oDiv.style.visibility = "hidden";
	}
}	

// This function sets the height of an iFrame to the height of the document it contains
function iFrameHeight()
{
	var h;

	if(document.getElementById && document.getElementById('iFrameName').contentDocument) 
	{
		var objFrame = document.getElementById('iFrameName');

		var objDoc = (objFrame.contentDocument) ? objFrame.contentDocument //IE5.5+, Moz 1.0+, Safari, Opera
			: (objFrame.contentWindow) ? objFrame.contentWindow.document
			: (window.frames && window.frames['iFrameName']) ? window.frames['iFrameName'].document //IE5
			: (objFrame.document) ? objFrame.document 
			: null;

		var objDocString = (objFrame.contentDocument) ? "document.getElementById('iFrameName').contentDocument" //IE5.5+, Moz 1.0+, Safari, Opera
			: (objFrame.contentWindow) ? "document.getElementById('iFrameName').contentWindow.document"
			: (window.frames && window.frames['iFrameName']) ? "window.frames['iFrameName'].document" //IE5
			: (objFrame.document) ? "document.getElementById('iFrameName').document" 
			: "null";

		objFrame.style.height = '1600px'; // Mozilla fix
 		h = (objDoc==null)?500:( (objDoc.documentElement.scrollHeight ? objDoc.documentElement.scrollHeight 
			: ( objDoc.body.scrollHeight ? objDoc.body.scrollHeight 
			: objDoc.body.offsetHeight) ) ); // find height of internal page
 		objFrame.style.height = h + 'px'; // change height of iFrame		
	}
	else if(document.all) 
	{
		var objFrame = document.frames('iFrameName');	
		h = document.frames('iFrameName').document.body.scrollHeight	
		document.all.iFrameName.style.height = h + 16 + 'px'; // + 16 for scrollbar width
	}
	document.getElementById("contentCell").style.height = h + 16 + "px";
}



// This function is executed when a change has been made on the image_media field.  The function
// shows a preview of the selected file and then uses IE only calls to determine the resolution and 
// size of the file.
function showPreview(file_name, btnUpload, useCallBack)
{		
	var ext, sShortFile_name, isValid
	var acceptedFiles = ".jpeg,.jpg,.png,.gif";
	ext = file_name.value.substr(file_name.value.length-4,4)
	sShortFile_name = file_name.value.substr( file_name.value.lastIndexOf("\\")+1 );
	isValid = true;

	if(sShortFile_name.length>100)
	{
		alert("The file name for the image may not be longer than 100 characters.");
		file_name.value="";
		document.getElementById(btnUpload).disabled = true;
		isValid = false;
	}
	else if(acceptedFiles.indexOf(ext.toLowerCase()) != -1)
	{/*	try		
	    {
		    if(gIsIE && !gIsIE7)
		    {
			    gIsProcessing = true;				
			    thisImage = new Image();
			    /* 
			    * ## B. Fail Safe the ShowPreview function ##
			    * -------------------------------------------------------	
			    * Added an onLoad event to ensure that the image was properly
			    * loaded before trying to access any of its features.
			    * (Special Note: The features are IE compatible only)
			    */
	 /*         thisImage.onload = function() 
			    {	
				    if(useCallBack) setImageFeatures(thisImage);
				    if(thisImage.fileSize>gMaxImageSizeLimit) 
				    {
					    isValid = false;
					    file_name.value="";
    				
					    document.getElementById(btnUpload).disabled = true;
    			
					    alert("This image is too large to upload. The max file size allowed is " + (gMaxImageSizeLimit/1024000) + " megs");					
				    }
				    else document.getElementById(btnUpload).disabled = false;
				    gIsProcessing = false;				
			    }
			    thisImage.src="File://" +file_name.value;
		    }		
		}
		catch(ex)
		{
		    isValid=true;
		}		*/
	}
	else
	{
		alert("This is not a valid Image File and will not be uploaded!");
		file_name.value="";
		document.getElementById(btnUpload).disabled = true;
		isValid = false;
	}
	
	document.getElementById(btnUpload).disabled = (gIsProcessing||!isValid);
	return isValid;
}

function submitForm(sFormID)
{		
	var oForm = document.getElementById(sFormID);
	var oMsg = document.getElementById("errorLabel");
	var msg = checkRequiredFields();

	if(msg=="") 
	{
		encryptFormKey(oForm);
		setProcessing(true, 'btn_submit');
		oForm.submit();	
	}
	else oMsg.innerHTML = "<font color='red'>"+msg+"</font>";
}

function checkRequiredFields()
{
	var msg = "";
	var value = trim(document.getElementById("firstName").value);
	if(value=="") msg += "First name is required.<br>";
	
	value = trim(document.getElementById("lastName").value);
	if(value=="") msg += "Last name is required.<br>";

	value = trim(document.getElementById("email").value);
	if(value=="") msg += "Email address is required.<br>";
	else if(!matchEmail(value)) msg += "Invalid email address given.<br>";

	value = trim(document.getElementById("phone").value);
	if(value=="") msg += "Phone number is required.<br>";
	else if(!matchPhone(value)) msg += "Wrong format for Phone Number.<br>";

	return msg;
}

// Used for form validation in order to protect against spammers
function encryptFormKey(oform){
    var sEmail = document.getElementById("email").value;
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);

    //alert(sPath + " - " + sPage);

    var sTempKey = sPage + sEmail;
    var sKey = getCheckSum(sTempKey);
    
    if(!document.getElementById("passKey"))
    {
        var newInput = document.createElement("input");
	newInput.type = "hidden";
        newInput.id = "passkey";
	newInput.value = sKey;
        newInput.name = "passkey";
        oform.appendChild(newInput);        
    }    
    else{
    document.getElementById("passkey").value = sKey;  
    }
    //alert(document.getElementById("passkey").value);
}

   
function getCheckSum( _sStr){
    var checkSum = 0;    
    for(var i=0; i < _sStr.length; i++){
        checkSum += _sStr.charCodeAt(i);
    }  
//alert("Checksum for :" + _sStr + " = " + checkSum);
    return checkSum;
}


//JS to open all external links in a new window
function dynamiclink(){
    var excludedomains=["idxready.com", "closerealty.com", document.domain]
    var excludedomains=excludedomains.join("|")
    rexcludedomains=new RegExp(excludedomains, "i")
    
    for (i=0; i<=(document.links.length-1); i++) {
    	if (document.links[i]){
            if (document.links[i].hostname.search(rexcludedomains)==-1&&document.links[i].href.indexOf("http:")!=-1){
                document.links[i].target="_blank"
            }
        }
    }
}
//window.onload=dynamiclink;