var current_user_state = "";
var dash_over = true;

Array.prototype.include = function(chosen_item) {
    for (var index = 0, len = this.length; index < len; ++index) {
        if (chosen_item == this[index])
            return true;
    }
    return false;
}

/* Utility Methods */


/* Accept/Cancel a reference request */

var ReferenceRequest = {
    accept: function(id) {
        $('accept_request_' + id).show();
        $('request_actions_' + id).hide();
    },
    cancel: function(id) {
        $('request_actions_' + id).show();
        $('accept_request_' + id).hide();
    }
}

function formatCurrency(num) {
    num = num.toString().replace(/$|,/g, '');
    if (isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
    num = num.substring(0, num.length - (4 * i + 3)) + ',' +
    num.substring(num.length - (4 * i + 3));
    return (((sign) ? '': '-') + num + '.' + cents);
}

/* Open/Close the edit reference form */

var EditReference = {
    open: function(id) {
        $('edit_reference_' + id).show();
        $('reference_statement_' + id).hide();
    },
    close: function(id) {
        $('edit_reference_' + id).hide();
        $('reference_statement_' + id).show();        
    }
}

var Specialization = {
    options: function() {
        return $H({
            'Real Estate Agent': ['', 'Commercial Real Estate Agent', 'Residential Real Estate Agent'],
            'Real Estate Broker': ['', 'Commercial Real Estate Broker', 'Residential Real Estate Broker'],
            'Real Estate Lender': ['', 'Commercial Lender', 'Residential Lender', 'Hard Money Lender', 'Private Money Lender'],
            'Contractor': ['', 'Carpenter', 'Electrical Contractor', 'Excavation Contractor',
                           'Fencing Contractor', 'Flooring Contractor', 'General Contractor',
                           'HVAC Contractor', 'Landscape Contractor', 'Plumbing Contractor',
                           'Roofing Contractor', 'Structural Engineer'],
            'Foreclosure Specialist': ['', 'Loss Mitigation Specialist']
        });
    },

    on_load: function() {
        with(Specialization) {
            toggle();
            append_options();
        }
    },
    
    on_change: function() {
        with(Specialization) {
            toggle();
            clear_options();
            append_options();
        }
    },

    toggle: function() {
        if (Specialization.options().keys().include($F('social_user_occupation'))) {
            $('social_user_specialization').up('.column').show();
        } else {
            $('social_user_specialization').up('.column').hide();
        }
    },

    clear_options: function(options) {
        field = $('social_user_specialization');
        Array.from(field.options).each(function(option) {
            field.remove(option);
        });
    },

    append_options: function(options) {
        field = $('social_user_specialization');

        Specialization.options().each(function(pair) {
            if ($F('social_user_occupation') == pair.key) {
                pair.value.each(function(option_name) {
                    html_option = document.createElement('option');
                    html_option.text = option_name;
                    html_option.value = option_name;
                    field.options.add(html_option);
                });
            }
        })
    }
}

var Messages = {
    loading: function(request) {
        $('messages_spinner').show();
    },

    display: function(request) {
        $('message_body').clear(); 
        Form.Element.clear('message_body');
        $('messages_spinner').hide();
        new Insertion.Bottom('messages_container', request.responseText);
    }
}

var Checkboxes = {
    ids: function() {
        h = document.createElement('input');
        h.setAttribute('type', 'hidden');
        h.setAttribute('name', 'ids');
        h.setAttribute('value', this.checked().join(','));

        return h;
    },

    form: function(url) {
        var f = document.createElement('form');
        f.style.display = 'none';
        document.body.appendChild(f);

        f.method = 'POST';
        f.action = url;

        h = this.ids();
        f.appendChild(h);

        return f;
    },

    checked: function() {
        return $$(this.checkbox_class).select(function(checkbox) {
            return checkbox.checked;
        }).collect(function(checkbox) {
            return checkbox.id;
        })
    }
}

var Conversations = new Object();
Object.extend(Conversations, Checkboxes);
Object.extend(Conversations, {
    checkbox_class: 'input.conversation_checkbox'
});

var ColleagueRequests = new Object();
Object.extend(ColleagueRequests, Checkboxes);
Object.extend(ColleagueRequests, { 
    checkbox_class: 'input.colleague_request_checkbox' 
});

var Colleagues = new Object();
Object.extend(Colleagues, Checkboxes);
Object.extend(Colleagues, { 
    checkbox_class: 'input.colleague_checkbox' 
});


Event.observe(window, 'load', function(event) {
    if ($('social_user_occupation') != undefined) {
        Specialization.on_load();

        Event.observe('social_user_occupation', 'change', function(event) {
            Specialization.on_change();
        });
    }
});

function hideEl(id) {
	$(id).setStyle({
		'visibility' : 'hidden'
	})
}

function destroy_me(el) {
	$(el).next('.should_destroy').value = 1;
	$(el).up('.attr_line').hide();
}

function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}

function clear_announcement(id) {
	set_cookie ("hide_announcement",id,2030,12,25);
	if(id == 0) {
		alert("Site-wide announcements will now be shown.");
	} else {
		$("sitewide_announcement").hide();
	}
}

function showAssocFee(value, id) {
	if (value == true) {
		$('property_association_fee_container_' + id).show();
	} else {
		$('property_association_fee_container_' + id).hide();
		$('property_association_fee_container_' + id).down('input[type="text"]').clear();
	}
}
function checkAndSetChkBoxValue(chkbox, target) {
	if ($(chkbox).checked == true) {
		$(target).value = 1;
	} else {
		$(target).value = 0;
	}
}

function getDim(el, dim) { 
	return parseInt(el.getStyle(dim).substring(0, el.getStyle(dim).length - 2)); 
}
function callBackStatusOn(o) { status = 1; }
function callBackStatusOff(o) { status = 0; }

function showSpinner() { $('spinner_container').show(); }
function hideSpinner() { $('spinner_container').hide(); }

function switchLoginForm() { $('please_log_in_message').toggle(); $('please_log_in_form').toggle(); }

function ttRef() {
	window.open("http://hobix.com/textile/quick.html","ttRef_window","height=600,width=550,channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=0,scrollbars=1,status=1,toolbar=0");
}

function switchSettingsTab(tab_id) {
  $$(".profile_settings_tab").each(function(e) {
		e.hide();
	});
	$$(".tab").each(function(e) {
		e.removeClassName("active");
	});
	$(tab_id).show();
	$("tab_" + tab_id).addClassName("active");
	$("tab_" + tab_id).removeClassName("inactive");
}

function clearBox(el, default_value) {
	if($F(el) == default_value) {
		$(el).clear();
	}
}

function restoreBox(el, default_value) {
	if($F(el) == "") {
		$(el).value = default_value;
	}
}

function petsChecks(id) {
    $('attr_' + id).value = "";
    $$('.tmpchk').each(function(s) {
        if (s.checked == true) {
            $('attr_' + id).value = $F('attr_' + id) + s.value + ",";
          }
    });
}
function updateLotSize(id) {
    var targetformat = $F('numformat_' + id);
    var targetvalue = $F('lot_size_value_' + id);
    if(isNaN(parseInt(targetvalue))) {
      targetvalue = 0;
    }
    //$('format_for_' + id).value = targetformat;
    if (targetformat == "acre") {
      targetvalue = targetvalue * 43560;
    }
    $('attr_' + id).value = targetvalue; 
}

function setQuoteText(target, value) {
  $(target).value = value;
}

function togglePasswordRow() {
    if ($('group_private').checked == true) {
        $('password_row').show();
    } else {
        $('password_row').hide();
    }
}

function showDashboardMenu(m) {
  $('ul_' + m).toggle();
}

function updateZip(country, target) {
	if(country == "US" || country == "United States") {
		label = "Zip Code";
	} else if (country == "UK" || country == "United Kingdom") {
		label = "Postcode"
	} else {
		label = "Postal Code";
	}
	
	if(target == "zip_p_lbl") {
		$(target).update(label);
	} else {
		$$('.zip').each(function(e) {
			e.up(1).down(0).update(label);
		});
	}
}

function updateState(country, target, switch_to) {
	
	var result;
	
	if(country == "US" || country == "United States") {
		label = "State";
	} else if (country == "UK" || country == "United Kingdom") {
		label = "County"
	} else if (country == "CA" || country == "Canada") {
		label = "Province";
	} else {
		label = "State / Region";
	}
	
	var xtra_qs = ""
	if (target == "property_state") {
		xtra_qs = "?target_obj=property&target_method=state";
	}
	
		var element_to_update = $(target).up(0);
		var field_fallback = '<input id="property_state" type="text" style="width: 140px;" size="30" name="property[state] "/>';
		
	new Ajax.Request('/users/get_state_options/' + country + xtra_qs, {
	  method: 'get',
	  onLoading: function(transport) {
			//element_to_update.update('<img src="/images/spinner_small.gif" alt="" />');
			element_to_update.update(field_fallback);
     },
	  onSuccess: function(transport) {
	   	result = transport.responseText;
	  },
		onFailure: function(transport) {
			result = field_fallback;
		},
		onComplete: function(transport) {
			
			element_to_update.update(result);
			
			if(target == "social_user_state") {
				changeSelectValue(target, current_user_state);
			}
			if(target == "property_state") {
				changeSelectValue(target, switch_to);
			}
		}
	});
	
	if (target != "property_state") {
		$(target).up(1).down(0).update(label);
	} else {
		$('state_p_lbl').update(label);
	}
	
}


var OldCookie = {
    set: function(name, value, daysToExpire) {
        var expire = '';
        if (daysToExpire != undefined) {
            var d = new Date();
            d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
            expire = '; expires=' + d.toGMTString();
        }
        return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
    },
    get: function(name) {
        var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
        return (cookie ? unescape(cookie[2]) : null);
    },
    erase: function(name) {
        var cookie = Cookie.get(name) || true;
        Cookie.set(name, '', -1);
        return cookie;
    },
    accept: function() {
        if (typeof navigator.cookieEnabled == 'boolean') {
            return navigator.cookieEnabled;
        }
        Cookie.set('_test', '1');
        return (Cookie.erase('_test') === '1');
    },

    enabled: function() {
        Cookie.set('_enabled_test', 'hey', 10);
        return (Cookie.get('_enabled_test') == 'hey');
    }
};



function updateRegZip() {
	updateZip($F('social_user_country'), 'zip_label');
}

function updateProfileBasics() {
	updateZip($F('social_user_country'));
	updateState($F('social_user_country'), 'social_user_state');
}

function updatePropertyBasics(switch_to) {
	updateZip($F('property_country'), 'zip_p_lbl')
	updateState($F('property_country'), 'property_state', switch_to);
}



    function changeSelectValue(target, value) {
        for (var x=0; x < $(target).length; x++) {
					if ($(target)[x].value == value) {
						$(target)[x].selected = true;
					}
				}
    }


function toggleSubmissionDate(value) {
	if (value == false) {
		$$('.submission_date_container').each(function(e) {
			e.show();
		})
	} else {
		$$('.submission_date_container').each(function(e) {
			e.hide();
		})
	}
}

function toggleAdSettings(checked) {
	if (checked) {
		$$('.ad_setting_row').each(function(e) {
			e.show();
		});
	} else {
		$$('.ad_setting_row').each(function(e) {
			e.hide();
		});
	}
}

function toggleGoogleAdSettings(checked) {
	if (checked) {
		$('use_google_ads').show();
		$$('.ad_content').each(function(e) {
			e.hide();
		});
	} else {
		$('use_google_ads').hide();
		$$('.ad_content').each(function(e) {
			e.show();
		});
	}
}

function showProfileRemaining() {
	$('profile_remaining').show();
	$('wdintd_link').hide();
}

var selected_recipients = [];
function addUsernameToRecipients(username, id) {
  if(selected_recipients.indexOf(id) == -1) {
    if($('conversation_speaker_usernames').value == "") {
        new_value = username;
    } else {
        new_value = $('conversation_speaker_usernames').value + ", " + username;
    }
      
    showSelectedFriend(id);
    $('conversation_speaker_usernames').value = new_value;
    selected_recipients.push(id);
  }
}

//    $("friend_" + id + "_added").show(); 
function showSelectedFriend(id) {
    jQuery("#friend_" + id).css({"background-color": "#ddd"});
//    new Insertion.Bottom('friend_' + id, " <img src='/images/added_small.png' class='added_sprite' alt='Added.'/>"); 
}


// Edd's super cool dynamic state selector.
var DynamicStateSelector = {
  
  states: function() {
        return $H({
          'United States': ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida","Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "Washington D.C.", "West Virginia", "Wisconsin", "Wyoming"],
          'Canada': ["Alberta", "British Columbia", "Manitoba", "New Brunswick", "Newfoundland", "Northwest Territories", "Nova Scotia", "Nunavut", "Ontario", "Prince Edward Island", "Quebec", "Saskatchewan", "Yukon"],
          'United Kingdom': ['Avon','Bedfordshire','Berkshire','Borders','Buckinghamshire','Cambridgeshire','Central', 'Cheshire','Cleveland','Clwyd','Cornwall','County Antrim','County Armagh','County Down','County Fermanagh','County Londonderry','County Tyrone','Cumbria','Derbyshire','Devon','Dorset','Dumfries and Galloway','Durham','Dyfed','East Sussex','Essex','Fife','Gloucestershire','Grampian','Greater Manchester','Gwent','Gwynedd County','Hampshire','Herefordshire','Hertfordshire','Highlands and Islands','Humberside','Isle of Wight','Kent','Lancashire','Leicestershire','Lincolnshire','Lothian','Merseyside','Mid Glamorgan','Norfolk','North Yorkshire','Northamptonshire','Northumberland','Nottinghamshire','Oxfordshire','Powys','Rutland','Shropshire','Somerset','South Glamorgan','South Yorkshire','Staffordshire','Strathclyde','Suffolk','Surrey','Tayside','Tyne and Wear','Warwickshire','West Glamorgan','West Midlands','West Sussex','West Yorkshire','Wiltshire','Worcestershire']});
    },
  
  filterCountryName: function(country) {
    var full_states = $H({"US":"United States", "UK":"United Kingdom", "CA":"Canada"});
    if(full_states.keys().include(country)) {
      country = full_states.get(country);
    }
    
    return country;
  },
  
  reverseFilterCountryName: function(country) {
    var full_states = $H({"United States":"US", "United Kingdom":"UK", "Canada":"CA"});
    if(full_states.keys().include(country)) {
      country = full_states.get(country);
    }
    
    return country;
  },

  generateStateSelect: function(state_el, country) {
    var select_with_options = "<select id=\"" + state_el + "\" name=\"" + $(state_el).name + "\"><option value=\"\"></option>";
    DynamicStateSelector.states().get(DynamicStateSelector.filterCountryName(country)).each(function(val) {
      select_with_options = select_with_options + "<option value=\"" + val + "\">" + val + "</option>"
    });
    return select_with_options + "</select>"
  },
  
  generateTextInput: function(state_el) {
    return "<input type=\"text\" id=\"" + state_el + "\" value=\"" + $F(state_el) + "\" name=\"" + $(state_el).name + "\">";
  },
  
  updateStateSelector: function(state_el, country) {
    country = DynamicStateSelector.filterCountryName(country);
    if (DynamicStateSelector.states().keys().include(country)) {
      var stateElementHtml = DynamicStateSelector.generateStateSelect(state_el, country);
    } else {
      var stateElementHtml = DynamicStateSelector.generateTextInput(state_el);
    }
    
    $(state_el).replace(stateElementHtml);
  },

  forceStateValue: function(state_el, state) {
    $(state_el).value = state;
  },

  init: function(country_el, state_el) {
    $(country_el).observe('change', function(e) {
      DynamicStateSelector.updateStateSelector(state_el, $F(country_el));
    });
  }
  
}

var UpgradeForm = {
  
  cycles: function() {
    return $H({"Monthly" : [ 1495.00, "/month", "monthly" ], "Yearly" : [ 15000.00, "/year", "yearly" ]});
  },
  
  cycleSelector: function() {
    selector_tag = "<select name=\"order[periodicity]\" id=\"order_periodicity\">"
    UpgradeForm.cycles().each(function(e) {
      selector_tag = selector_tag + "<option value=\""+e[1][2]+"\">"+e[0]+" ($"+e[1][0]/100+" "+e[1][1]+")</option>"
    });
    document.write(selector_tag + "</select>");
    $('order_periodicity').observe('change', function(e) {
      UpgradeForm.updateImmediatePaymentIndicator($F('order_periodicity'));
    });
  },
  
  updateImmediatePaymentIndicator: function(value) {
    if(value == "monthly") { var payment = "$14.95" } else { var payment = "<strike>$179.40</strike> $150.00" }
    $('payment_today').update(payment);
  }
  
}





// containers
var openTags = [];
var setCaretPos = 0;
// color settings
var openClr = "#ff0000"; // "#aaa"
var closedClr = "#000";

function getCaretPosition(oField) {
  var iCaretPos = 0;
  if (document.selection) { 
    oField.focus();
    var oSel = document.selection.createRange ();
    oSel.moveStart ('character', -oField.value.length);
    iCaretPos = oSel.text.length;
  }
  else if (oField.selectionStart || oField.selectionStart == '0')
    iCaretPos = oField.selectionStart;
  return (iCaretPos);
}

function setCaretPosition(oField, iCaretPos) {
  if (document.selection) { 
    oField.focus();
    var oSel = document.selection.createRange ();
    oSel.moveStart ('character', -oField.value.length);
    oSel.moveStart ('character', iCaretPos);
    oSel.moveEnd ('character', 0);
    oSel.select ();
  }
  else if (oField.selectionStart || oField.selectionStart == '0') {
    oField.selectionStart = iCaretPos;
    oField.selectionEnd = iCaretPos;
    oField.focus();
  }
}

function insertAtCursor(myField, myValue) {
  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  } else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)
      + myValue
      + myField.value.substring(endPos, myField.value.length);
      setCaretPosition(myField, (startPos + myValue.length));
  } else {
      myField.value += myValue;
  }
}

function tag_is_open(tag) {
  if (openTags.indexOf(tag) >= 0) {
    return true;
  } else {
    return false;
  }
}

function updateBtn(btn, clr) {
  $('btn_' + btn).setStyle({
    color: clr
  })
}

function toggleTag(tag, el) {
  if (!tag_is_open(tag)) {
    openTags[openTags.length] = tag;
    insertAtCursor(el, "[" + tag + "]");
    updateBtn(tag, openClr);
  } else {  
    openTags[openTags.indexOf(tag)] = null;
    openTags.compact();
    insertAtCursor(el, "[/" + tag + "]");
    updateBtn(tag, closedClr);
  }
  el.focus();
}

function showPropertyStats(property_id) {
  $$('.property_stats_container').each(function(e) {
    e.hide();
  });
  $('property_stats_' + property_id).show();
}


function showBubble(target, message) {
  Element.insert(target, { 'after' : "<div class=\"helpBubble\">" + message + "</div>" } );
}

function clearAllBubbles() { $$('.helpBubble').each(function(e) { e.hide(); }); }

function showQuestionAnswer(question_id) {
  Effect.toggle("question_answer_" + question_id, 'slide');
}

function showParticipantTab(tab) {
  $$('.part_link').each(function(e) {
    e.removeClassName("selected_participant_tab_link");
  });
  $$('.top_participant_container').each(function(e) {
    e.hide();
  });
  $('top_' + tab + '_container').show();
  $('part_link_' + tab).addClassName("selected_participant_tab_link");
}

