// Contact form staus flag
var contact_form_error = false;

// stuffs agent_uid into global javascript
var agent_uid = '0';

var oCaptchaIDList = ['av_contact_recaptcha_widget', 'blog_comment_recaptcha_widget'];
var oCaptchaNode;

//================================================================
function TrackingObj() {
 this.covered_aid=0;
 this.covered_zip='';
 this.not_covered_zip='';
 this.not_found_addr='';
 this.not_found_csz='';
}
var tracking_obj=new TrackingObj();

//pixel tracking function
function makeHvTracking(pixel_name, tab_name){
  if ( typeof(oHGMap) != 'undefined' ){
      if(oHGMap.homeValuationStatus == 'success') {
      } else {
        tracking_obj.not_found_addr = getFlagInCookie('ck_hval_user_entered','strAddress');
        tracking_obj.not_found_csz  = getFlagInCookie('ck_hval_user_entered','strCSZ');
      }

        if(pixel_name=='covered') {
          tracking_obj.covered_aid=agent_uid;
          tracking_obj.covered_zip= oHGMap.g_zip;
        } else if (pixel_name=='not_covered') {
          tracking_obj.not_covered_zip= oHGMap.g_zip;
          }   

      if (tab_name == 'home_value'){
        dcsMultiTrack('DCSext.tag_hval_covered_aid', tracking_obj.covered_aid , 'DCSext.tag_hval_covered_zip', tracking_obj.covered_zip , 'DCSext.tag_hval_not_covered_zip', tracking_obj.not_covered_zip , 'DCSext.tag_hval_not_found_addr', tracking_obj.not_found_addr , 'DCSext.tag_hval_not_found_csz', tracking_obj.not_found_csz , 'WT.cg_n', 'AgentView' , 'WT.cg_s', 'HomeValues;HomeValuesTab' ); }
      else if (tab_name == 'local_info'){
        dcsMultiTrack('DCSext.tag_hval_covered_aid', tracking_obj.covered_aid , 'DCSext.tag_hval_covered_zip', tracking_obj.covered_zip , 'DCSext.tag_hval_not_covered_zip', tracking_obj.not_covered_zip , 'DCSext.tag_hval_not_found_addr', tracking_obj.not_found_addr , 'DCSext.tag_hval_not_found_csz', tracking_obj.not_found_csz , 'WT.cg_n', 'AgentView' , 'WT.cg_s', 'LocalInfo;LocalInfoTab' ); }
      else {
        dcsMultiTrack('DCSext.tag_hval_covered_aid', tracking_obj.covered_aid , 'DCSext.tag_hval_covered_zip', tracking_obj.covered_zip , 'DCSext.tag_hval_not_covered_zip', tracking_obj.not_covered_zip , 'DCSext.tag_hval_not_found_addr', tracking_obj.not_found_addr , 'DCSext.tag_hval_not_found_csz', tracking_obj.not_found_csz , 'WT.cg_n', 'AgentView' , 'WT.cg_s', 'ContactAgent;HomeValuesTab' ); }
  }
}
function getCaptchaNode(id_list) {
    for ( id in id_list ) {
        if ( document.getElementById(id_list[id]) != null ) {
            return document.getElementById(id_list[id]);
        }
    }
    return null;
}
function moveCaptcha(obj_node, source_form_id, target_div_id) {
    var bSourceExists = !(obj_node == null);

    if ( bSourceExists ) {
        // Get the captcha source form node.
        oSourceFormNode = document.getElementById(source_form_id);
        
        // This assumes that we've defined a div having the same name as the captcha div with "_placeholder" appended to the end.
        // The captcha node will be inserted before the placeholder div.
        var oTargetPlaceholderNode = document.getElementById(target_div_id + '_placeholder');
        var oTargetPlaceholderParentNode = oTargetPlaceholderNode.parentNode;

        // Remove the captcha mode from the source form node.
        try {
            oSourceFormNode.removeChild(obj_node);
        } catch (err){ }

        // Insert the captcha node before the placeholder.
        oTargetPlaceholderParentNode.insertBefore(obj_node, oTargetPlaceholderNode);
    }
}
function showForm(show_form, module_height){
	/*
		2008-10-23 - JC BUG6264 - In IE 6 the state select drop-down shows through the contact form so we'll have to check
		to see if the select list exists and if so change its display style when the contact module is
		shown/hidden.
	*/
	var bStateSel = false;
        if (typeof(module_height) == 'undefined') {
            var module_height = 503;
        }

	//hfs_form_short
	if ( typeof(document.profiles_form_short) != 'undefined' ){
		oStateSel = document.profiles_form_short.state;
		bStateSel = true;
	} else if ( typeof(document.hfs_form_short) != 'undefined' )
	{
		oStateSel = document.hfs_form_short.state;
		bStateSel = true;
	}
    //debugger;
    // Get captcha node.
    oCaptchaNode = ( typeof(oCaptchaNode) != 'undefined' && oCaptchaNode != null ? oCaptchaNode : getCaptchaNode(oCaptchaIDList));
    //alert(oCaptchaNode);

    oBlogCommentCaptchaNode = document.getElementById('blog_comment_recaptcha_widget');
    bBlogReCaptcha = !(oBlogCommentCaptchaNode == null);
	
    if(show_form == "hide"){
        // RFC5139 - In the future we want to try to allow 2 reCaptcha widgets in the same page.

        if ( bBlogReCaptcha ) {
            // captcha node, source_form_id, target_div_id
            moveCaptcha(
                oCaptchaNode, 
                'contactForm', 
                'blog_comment_recaptcha_widget'
            );
        }

		if (bStateSel)
		{
			oStateSel.style.display = "inline";
		}
		document.getElementById('contact_module').style.height = '160px';
		document.getElementById('form_center').style.height = '133px';
		document.getElementById('extended_fields').style.display = 'none';
		document.getElementById('close_btn').style.display = 'none';
		if(eval(document.getElementById('error_msg'))) document.getElementById('error_msg').style.display = 'none';
		document.getElementById('form_icon').href = "javascript:showForm('show', " + module_height + ");";
		document.getElementById('form_icon').innerHTML = "<img src=\"http://images.homegain.com/i/hval/expand_ico.gif\" />";
	}
	else {
        // RFC5139 - In the future we want to try to allow 2 reCaptcha widgets in the same page.
        // RFC?
        //  captcha node, source_form_id, target_div_id
        moveCaptcha(
            oCaptchaNode,
            'frmBlogComment',
            'av_contact_recaptcha_widget'
        );
        
		if(show_form =="show" && !contact_form_error) {
			if (bStateSel)
			{
				oStateSel.style.display = "none";
			}
                        document.getElementById('contact_module').style.height = module_height + 'px';
                        document.getElementById('form_center').style.height = (module_height - 27) + 'px';
			document.getElementById('extended_fields').style.display = 'block';
			document.getElementById('close_btn').style.display = 'block';
			document.getElementById('form_icon').href = "javascript:showForm('hide', " + module_height + ");";
			document.getElementById('form_icon').innerHTML = "<img src=\"http://images.homegain.com/i/hval/collapse_ico.gif\" />";

			if(agent_uid != "0") makeHvTracking('covered','contact_agent');
			else makeHvTracking('not_covered','contact_agent');
		}

		if(show_form == "error" || contact_form_error) {
			if (bStateSel)
			{
				oStateSel.style.display = "none";
			}
                        document.getElementById('contact_module').style.height = (module_height + 120) + 'px';
                        document.getElementById('form_center').style.height = (module_height + 93) + 'px';
			document.getElementById('extended_fields').style.display = 'block';
			document.getElementById('close_btn').style.display = 'block';
			document.getElementById('error_msg').style.display = 'block';
			document.getElementById('form_icon').href = "javascript:showForm('hide', " + module_height + ");";
			document.getElementById('form_icon').innerHTML = "<img src=\"http://images.homegain.com/i/hval/collapse_ico.gif\" />";
			contact_form_error = true;
		}
	}
}

//================================================================
function showTab(tab_name){
	// hides all modules
	document.getElementById('home_value').className = 'home_value off';
	document.getElementById('local_info').className = 'local_info off';
	// deactivates all tabs
	document.getElementById('home_value_tab').className = 'tab_inactive';
	document.getElementById('local_info_tab').className = 'tab_inactive';
	// activates selected tab and displays selected module
	document.getElementById(tab_name).className = tab_name + ' on';
	document.getElementById(tab_name + '_tab').className = 'tab_active';

        if(agent_uid != "0") makeHvTracking('covered',tab_name);
	else makeHvTracking('not_covered',tab_name);
}

//================================================================
function displayDataChart(chart, state, zip){
	var html = "";
	var maxFlashVersion = 9;
	var minFlashVersion = 0;
	var FlashRevision = 8;
	var hasFlash = DetectFlashVer(maxFlashVersion, minFlashVersion, FlashRevision);
	if(hasFlash){
		html = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"750\" height=\"450\" align=\"middle\">";
		html += "<param name=\"allowScriptAccess\" value=\"sameDomain\" />";
		html += "<param name=\"movie\" value=\"/media/" + chart + ".swf\" />";
		html += "<param name=\"quality\" value=\"high\" />";
		html += "<param name=\"wmode\" value=\"transparent\" />";
		html += "<param name=\"FlashVars\" value=\"stateAbbr=" + state + "&zipCode=" + zip + "\" />";
		html += "<embed src=\"/media/" + chart + ".swf\" FlashVars=\"stateAbbr=" + state + "&zipCode=" + zip + "\" wmode=\"transparent\" quality=\"high\" width=\"750\" height=\"450\" align=\"middle\" allowscriptaccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />";
		html += "</object>";
	} else {
		html = "<br/><p class='alert' style='margin:30px 10px;font-family:arial;font-size:12px;'>Please <a href='http://www.adobe.com/go/getflash' target='_blank'>get the latest Flash player</a> to view this feature.</p><br/>";
	}
	document.getElementById(chart + "_flash").innerHTML = html;
}

//================================================================
function checkFieldStatus(form_field, has_focus){
	
	// checks message field
	if(form_field.name == 'message'){
		if(has_focus){
			form_field.style.color = "#000000";
			if(form_field.value == 'Enter your message here') form_field.value = "";
		} else {
			if(form_field.value == ''){
				form_field.value = "Enter your message here";
				form_field.style.color = "#999999";
			}
		}
	}
}

//================================================================
function initFieldStatus(){
	// checks message field
	if(document.contactForm.message.value == '' || document.contactForm.message.value == 'Enter your message here'){
		document.contactForm.message.value = "Enter your message here";
		document.contactForm.message.style.color = "#999999";
	}
}

//================================================================
function validateForm(form){
    // 2008-10-13 - JC - RFC5071/BUG6238
    // Due to caching of the homevalues, when we submit the contact form for the landing page, we want to 
    // post to /homevalues/ so the non-cached page is requested. Otherwise the email will not be sent.
    if ( location.pathname.toLowerCase() == '/homevalues' ) {
        form.action = '/homevalues/';
    }
    
	if(form.message.value == 'Enter your message here') form.message.value = "";
	// 2008-10-22 - JC - RFC5139
	document.getElementById('submit_btn').innerHTML = "<div style='padding-bottom: 7px;'>&nbsp;&nbsp;processing...&nbsp;&nbsp;</div>";
    
    if ( document.getElementById('local_info') && document.getElementById('local_info').className == 'local_info on' ) {
        var oForm = document.contactForm;
        var oElt = document.createElement('input');
        
        oElt.setAttribute('id', 'tab');
        oElt.setAttribute('name', 'tab');
        oElt.setAttribute('type', 'hidden');
        oElt.setAttribute('value', '2');
        
        oForm.appendChild(oElt);
    }
    
	return true;
}
//================================================================
//  Description:
//      FieldWatermark object & related functions
//  
//  Purpose:
//      This object is bound to a form field and can be used to 
//      control display of "watermark" text...although it's 
//      not really a "watermark" since it doesn't display
//      when text is entered in the field.
//
//  Date:
//      2008-04-03        
//================================================================
function FieldWatermark(form_id, field_id, wm_text) {
    this.id         = field_id;
    this.text       = wm_text;
    this.colorOn    = "#999999";
    this.colorOff   = "#000000";
    this.formField  = document.getElementById(field_id);
    this.form       = document.getElementById(form_id);
    
    this.createView();
    this.toggle("blur");
}
//================================================================
FieldWatermark.prototype.toggle = function (event_type) {
    if ( event_type == "focus" ) {
        if ( this.formField.value.length == 0 ) {
            // Remove watermark.
            this.formField.value        = "";
            this.formField.style.color  = this.colorOn;
        }
        else {
            // If the field has the watermark text, then blank it out and set color to colorOff. 
            if ( this.formField.value == this.text ) {
                this.formField.value        = "";
                this.formField.style.color  = this.colorOff;
            }
        }
    }
    else if ( event_type == "blur" ) {
        //alert("blurring " + this.id + ", len: " + this.formField.value.length);
        
        if ( this.isEmpty() ) {
            // Display watermark.
            this.formField.value        = this.text;
            this.formField.style.color  = this.colorOn;
        }
        else {
            // Do not display watermark.
            this.formField.style.color = this.colorOff;
        }
    }
}
//================================================================
FieldWatermark.prototype.hasWatermark = function() {
    return ( this.formField.value == this.text );
}
//================================================================
FieldWatermark.prototype.isZeroLength = function() {
    return ( this.formField.value.length == 0 );
}
//================================================================
FieldWatermark.prototype.isEmpty = function() {
    return ( this.hasWatermark() || this.isZeroLength() );
}
//================================================================
FieldWatermark.prototype.createView = function() {
    this.formField.modelObj = this;
    this.formField.onblur   = fieldEventHandler;
    this.formField.onfocus  = fieldEventHandler;
}
//================================================================
FieldWatermark.prototype.validate = function () {
    // All we want to do is clear watermark text if it's there, otherwise it'll be submitted with the form.
    
    if ( this.formField.value == this.text ) {
        //alert("Clearing " + this.id);
        this.formField.value = "";
    }
}
//================================================================
function fieldEventHandler(event){
    var oModel = this.modelObj;
    var oEvent = ( event ? event : window.event );
    
    if ( oModel ) {
        oModel.toggle(oEvent.type);
    }
    return true;
}
//================================================================
//  stripInvalidAddress
//================================================================
function validateHVForm(form) {
    //var bEmptyAddress   = ( oAddrFieldWaterMark.isEmpty() && oCSZFieldWaterMark.isEmpty() );
    var bEmptyAddress   = oCSZFieldWaterMark.isEmpty();
    
    // Since the fields' onblur handlers will be invoked on form submit, "empty" fields will contain the watermark text.
    // If both of them do, we'll consider that empty. Otherwise, we'll call each fields' validate() method to clear the watermark.
    
    if ( !bEmptyAddress ) {
        if ( typeof(arrFields) != "undefined" ) {
            // Clear watermarks when necessary.
            //oAddrFieldWaterMark.validate();
            oCSZFieldWaterMark.validate();
        }
        return getHVALAddress(form);
    }
    else {
        //oAddrFieldWaterMark.toggle("blur");
        oCSZFieldWaterMark.toggle("blur");
        
        alert("Please enter a street address OR a city, state or zip.");
        
        return false;
    }
    
}
//================================================================
//  Submission processing for homes (homescout) search forms
//================================================================
function processHSForm(obj_form) {
    //debugger;
    var oForm = obj_form; //document.forms[form_name];
    var strCity = oForm.city.value.replace(/\s/gi, "-");
    var strState = oForm.state.options[oForm.state.options.selectedIndex].value;
    
    strCity = escape(strCity.replace(/[\/\\%<>#\{\}\[\]\|~^`'"@]/g, ""));
    
	 if (strState == '__none__' && strState == '' && strCity == '') {
	 	oForm['action'] = '/homes/' + strCity + '-' + strState;
	 } else if (strState == '__none__') {
	 	var strState = '';
		oForm['action'] = '/homes/' + strCity + '-' + strState;
	 } else if (strCity == '') {
	 	oForm['action'] = '/homes/' + strCity + '-' + strState;
	 } else {
    	oForm['action'] = '/homes/' + strCity + '-' + strState;
	 }
}
//================================================================