//initialise
function init(){
	initScrollable();
}

function initScrollable(){
	document.getElementById('scrollableLoading').style.display = 'none';
	document.getElementById('allScrollable').style.display = 'block';
	var scrollableOptns = {
		circular:true
	};
	var navigatorOptns = {
		navi:'ul#navi'
	};
	$(function() {
		// initialize scrollable
		$(".scrollable").scrollable(scrollableOptns).navigator(navigatorOptns);
	});
}

//trim function
function trim(s){
	return s.replace(/(^\s+)|(\s+$)/g, "");
}

function toggle_visibility(x){
	if(document.getElementById(x).style.display=="block") document.getElementById(x).style.display="none";
	else document.getElementById(x).style.display="block";
}

function show(x){
	document.getElementById(x).style.display="block";
}

function hide(x){
	document.getElementById(x).style.display="none";
}

function toggle_visibilityv(x){
	if(document.getElementById(x).style.visibility=="collapse") document.getElementById(x).style.visibility="visible";
	else document.getElementById(x).style.visibility="collapse";
}

function apply_class(x,y){
		document.getElementById(x).className=y;
}


function show_row(x){
		document.getElementById(x).className='show_row';
}

function hide_row(x){
		document.getElementById(x).className='hide_row';
}

function select_row(x){
	document.getElementById(x).className='selected_orange';
}

function unselect_row(x){
	document.getElementById(x).className='';
}

function toggle_class(x,y){
		if(document.getElementById(x).className==y) document.getElementById(x).className="";
		else document.getElementById(x).className=y;
}

function toggle_class_plus(x,y){
		if(document.getElementById(x).className==y) document.getElementById(x).className="plus";
		else document.getElementById(x).className=y;
}

function toggle_class_x(x,y){
		if(document.getElementById(x).className==y) document.getElementById(x).className="help_sel";
		else document.getElementById(x).className=y;
}

function toggle_check(x){
		document.getElementById(x).checked = !document.getElementById(x).checked;
}

function toggle_pm(){
	toggle_class_plus('pm','pm_selected'); toggle_visibility('property_menu'); toggle_visibility('pm_f');	
}

function edit_property(id){
		window.open('popup_edit_property.html','Edit property ','menubar=no,width=720,height=600,toolbar=no,scrollbars=1');
}

function preview_property(id){
		window.open('popup_property_description_preview.html','PreviewProperty','menubar=no,width=780,height=600,toolbar=no,scrollbars=1');
}


function toggleAllCBoxes(theForm,field,value)
{
    for (i=0; i<theForm.elements.length; i++) {
        if (theForm.elements[i].name==field)
            theForm.elements[i].checked = value;
    }
}

function validate_addproperty(x,y){
	//sales
	if(y == 'sale'){
		if(x.acceptTerms.checked == false) { 
			alert('You must agree the Terms and Conditions of the listing.'); 
		} 
		else if(x['data[user_ref]'].value == '' || x['data[title]'].value == '' || x['data[town]'].value == '' || x['data[postcode]'].value == '' || x['data[borough]'].value == '' || x['data[property_type]'].value == 'please select' || x['data[bedrooms]'].value == 'please select' || x['data[price]'].value == '') {
			alert('Please insert required information. Thank you.');	
		}
		else { 
			x.submit(); 
			buildWorkingBox('Saving...');
		}
	} 
	
	//overseas sales
	if(y == 'osales'){
		if(x.acceptTerms.checked == false) { 
			alert('You must agree the Terms and Conditions of the listing.'); 
		} 
		else if(x['data[user_ref]'].value == '' || x['data[title]'].value == '' || x['data[country]'].value == '' || x['data[region]'].value == ''  || x['data[property_type]'].value == '' || x['data[bedrooms]'].value == '' || x['data[price]'].value == '') {
			alert('Please insert required information. Thank you.');	
		}else{ 
			x.submit(); 
			buildWorkingBox('Saving...');
		}
	} 
	
	//lettings
	if(y == 'lettings'){
		if(x.acceptTerms.checked == false) { 
			alert('You must agree the Terms and Conditions of the listing.'); 
		} 
		else if(x['data[user_ref]'].value == '' || x['data[title]'].value == '' || x['data[town]'].value == '' || x['data[postcode]'].value == '' || x['data[borough]'].value == '' || x['data[property_type]'].value == 'please select' || x['data[bedrooms]'].value == 'please select' || x['data[price]'].value == '' || x['data[price_type]'].value == 'please select') {
			alert('Please insert required information. Thank you.');	
		}
		else { x.submit();buildWorkingBox('Saving...'); }
	} 
	
	//overseas lettings
	if(y == 'olettings'){
		if(x.acceptTerms.checked == false) { 
			alert('You must agree the Terms and Conditions of the listing.'); 
		} 
		else if(x['data[user_ref]'].value == '' || x['data[title]'].value == '' || x['data[country]'].value == '' || x['data[region]'].value == '' || x['data[property_type]'].value == '' || x['data[bedrooms]'].value == '' || x['data[price]'].value == '') {
			alert('Please insert required information. Thank you.');	
		}
		else { x.submit();buildWorkingBox('Saving...'); }
	} 
}

function convertPrice(priceType, initialPrice){
	var result = -1;
	switch (priceType) {
		case "PM": result = initialPrice; break;
		case "PA":  result = Math.round((initialPrice  / 12) * 100)  / 100; break;
		case "PW": result = Math.round((initialPrice * 4.5)  * 100) / 100; break;
		default:break; 
	}
//	alert(result);
	return result;	
}


//gets a document element by ID
function getObyID(id){
	return document.getElementById(id);	
}


function validate_myDetails(x,y){
	if(y == 'Individual'){
		if( x['register[contact_name]'].value == '' || 
			x['register[contact_tel]'].value == '' || 
			x['register[address1]'].value == '' || 
			x['register[contact_name]'].value == '' || 
			x['register[town]'].value == '' || 
			x['register[county]'].value == '' || 
			x['register[postcode]'].value == '') {
				alert('Please insert required information. Thank you.');	
			}	else { x.submit(); }
	}
	
	if(y == 'Agent'){
		if( x['register[contact_name]'].value == '' || 
			x['register[contact_tel]'].value == '' || 
			x['register[address1]'].value == '' || 
			x['register[contact_name]'].value == '' || 
			x['register[town]'].value == '' || 
			x['register[county]'].value == '' || 
			x['register[postcode]'].value == '') {
				alert('Please insert required information. Thank you.');	
			}	else { x.submit(); }
	}
	
	if(y == 'Private Landlord'){
		if( x['register[contact_name]'].value == '' || 
			x['register[contact_tel]'].value == '' || 
			x['register[address1]'].value == '' || 
			x['register[contact_name]'].value == '' || 
			x['register[town]'].value == '' || 
			x['register[county]'].value == '' || 
			x['register[postcode]'].value == '') {
				alert('Please insert required information. Thank you.');	
			}	else { x.submit(); }
	}
	
	if(y == 'Private Vendor'){
		if( x['register[contact_name]'].value == '' || 
			x['register[contact_tel]'].value == '' || 
			x['register[address1]'].value == '' || 
			x['register[contact_name]'].value == '' || 
			x['register[town]'].value == '' || 
			x['register[county]'].value == '' || 
			x['register[postcode]'].value == '') {
				alert('Please insert required information. Thank you.');	
			}	else { x.submit(); }
	}
	
	if(y == 'Conveyancer'){
		if( x['register[contact_name]'].value == '' || 
			x['register[contact_tel]'].value == '' || 
			x['register[address1]'].value == '' || 
			x['register[contact_name]'].value == '' || 
			x['register[town]'].value == '' || 
			x['register[county]'].value == '' || 
			x['register[postcode]'].value == '') {
				alert('Please insert required information. Thank you.');	
			}	else { x.submit(); }
	}
	
	if(y == 'Hip Provider'){
		if( x['register[contact_name]'].value == '' || 
			x['register[contact_tel]'].value == '' || 
			x['register[address1]'].value == '' || 
			x['register[contact_name]'].value == '' || 
			x['register[town]'].value == '' || 
			x['register[county]'].value == '' || 
			x['register[postcode]'].value == '') {
				alert('Please insert required information. Thank you.');	
			}	else { x.submit(); }
	}
	
	if(y == 'Mortgage Specialist'){
		if( x['register[contact_name]'].value == '' || 
			x['register[contact_tel]'].value == '' || 
			x['register[address1]'].value == '' || 
			x['register[contact_name]'].value == '' || 
			x['register[town]'].value == '' || 
			x['register[county]'].value == '' || 
			x['register[postcode]'].value == '') {
				alert('Please insert required information. Thank you.');	
			}	else { x.submit(); }
	}
}

function zoomPhoto(file){
	window.open(file,null,'toolbar=0,location=0,scrollbars=0,statusbar=0,menubar=0,resizable=0,width=800,height=600');
}

//home page search box text
var emptySearchBoxText;
var searchBoxRef;
var initFocus = true;
function onHomeSearchFocus() {
	if(initFocus){
		initFocus = false;
		searchBoxRef = document.getElementById('location');
		emptySearchBoxText = searchBoxRef.value;
		searchBoxRef.value = "";
	}else{
		var boxValue = searchBoxRef.value;
		if(boxValue==emptySearchBoxText){
			searchBoxRef.value = "";
		}
	}
}
function onHomeSearchBlur() {
	var boxValue = trim(searchBoxRef.value);
	if(boxValue==""){
		searchBoxRef.value = emptySearchBoxText;
	}
}

/* advertise forms show/hide */
$(document).ready(function () {
	$('a.advertisePropertyTrigger').click(function () {
		$('div#advertisePropertyForm').slideToggle('medium');
	})
})

$(document).ready(function () {
	$('a.advertiseBusinessTrigger').click(function () {
		$('div#advertiseBusinessForm').slideToggle('medium');
	})
})

/* generic show/hide of 'other' fields as required: 1-text, 2-check boxes */
function checkOtherDropDown(field){
	var otherFieldDiv = document.getElementById(field.id + "Other");
	if (document.getElementById(field.id).value == "Other") {
		otherFieldDiv.style.display = "block";
	}else{
		otherFieldDiv.style.display = "none";
	}
}

	function checkOtherCheckbox(field){
 	var otherFieldDiv = document.getElementById(field.id + "Other");
	if(field.checked){
		otherFieldDiv.style.display = "block";
	}else{
		otherFieldDiv.style.display = "none";
	}
	}

/* generic text box blur/focus with default value show/hide */
var textFields = new Array();

function array_key_exists(key, search){
	if (!search || (search.constructor !== Array && search.constructor !== Object)){
		return false;
	}
	return key in search;
}

function trim(s){
	return s.replace(/(^\s+)|(\s+$)/g, "");
}

function onTextBoxFocus(field){
	var fieldValue = field.value;
	if(!array_key_exists(field.id, textFields)){
		textFields[field.id] = fieldValue;
	}
	if(fieldValue==textFields[field.id]){
		field.value = "";
	}
}

function onTextBoxBlur(field){
	var fieldValue = trim(field.value);
	if(fieldValue==""){
		field.value = textFields[field.id];
	}
}

/* checks and limits a textarea's number of characters */
function checkNumChars(field, limit){
	var comments = field.value;
 	var numChars = comments.length;
	var numCharsDisplay = document.getElementById(field.id+"NumChars");
	field.value = field.value.substring(0, limit);
	numChars = field.value.length;
	numCharsDisplay.innerHTML = "("+numChars+" / "+limit+")";
 }
 
 /* Estate agents search box */
function onAgentBoxBlur(field){
	var fieldValue = trim(field.value);
	if(fieldValue==""){
		field.value = "Enter estate agent name, area or postcode";
	}
}

function onAgentBoxFocus(field){
	var fieldValue = trim(field.value);
	if(fieldValue=="Enter estate agent name, area or postcode"){
		field.value = "";
	}
}

/* County slider */
function slideCounty(field){
	var triggerId = field.id;
	var county = triggerId.replace("Trigger", "");
	toggleCountyHeaderCss(county);
	var divToShow = county+"Target";
	$('div#'+divToShow).slideToggle('medium');
}

function toggleCountyHeaderCss(county){
	var header = document.getElementById(county+"Header");
	var classType = header.className;
	if(classType=="countyHeaderOpen"){
		header.className = "countyHeaderClosed";
	}else if(classType=="countyHeaderClosed"){
		header.className = "countyHeaderOpen";
	}
}

/* select london search type */
function changeLondonSearchType(field){
	var url = field.options[field.selectedIndex].value;
	window.location = "http://www.mintlocation.com"+url;
}

function showRegisterPopup(){
	grayOut(true);
	document.getElementById('registerPopup').style.display = 'block';
}
function hideRegisterPopup(){
	grayOut(false);
	document.getElementById('registerPopup').style.display = 'none';
}
/* Greys out the screen */
function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = 1000;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
     if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
    } else{
		var pageWidth='100%';
       var pageHeight='100%';
	}
	if(navigator.userAgent.indexOf("Firefox")!=-1){
		pageWidth='100%';
       	pageHeight='100%';
	}
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';                          
  } else {
     dark.style.display='none';
  }
}

/* Add new image rows to the property manager INSERT form */ 
function insertAfter( referenceNode, newNode ){
    referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
//starts at 3 as 3 already present
var curImgRow = 3;
var maxAllowed = 15; //NOTE: this is updated in some of the property manager EDIT files
function addImgRow(){
	if(curImgRow<maxAllowed){
		//remove old button
		var btnContainer = document.getElementById('inputTd'+curImgRow);
		var oldBtn = document.getElementById('addImgBtn');
		btnContainer.removeChild(oldBtn);
		//create nodes
		var tableRow = document.createElement('tr');
		tableRow.setAttribute('id','imgRow'+(curImgRow+1));
		var titleTd = document.createElement('td');
		titleTd.setAttribute('width','160');
		titleTd.setAttribute('class','nobordertop');
		var strongTitle = document.createElement('strong');
		strongTitle.innerHTML = "Image "+(curImgRow+1);
		var inputTd = document.createElement('td');
		inputTd.setAttribute('width','540');
		inputTd.setAttribute('class','grey');
		inputTd.setAttribute('id','inputTd'+(curImgRow+1));
		var imgInputField = document.createElement('input');
		imgInputField.setAttribute('type','file');
		imgInputField.setAttribute('name', 'image'+curImgRow);
		//begin to append nodes
		titleTd.appendChild(strongTitle);
		inputTd.appendChild(imgInputField);
		//check if add button is needed
		if(curImgRow<(maxAllowed-1)){
			var addRowBtn = document.createElement('input');
			addRowBtn.setAttribute('class','widthheightauto');
			addRowBtn.setAttribute('type','button');
			addRowBtn.setAttribute('id','addImgBtn');
			addRowBtn.setAttribute('value','Add another image');
			addRowBtn.setAttribute('onclick',"addImgRow();");
			inputTd.appendChild(addRowBtn);
		}
		//finish appending nodes
		tableRow.appendChild(titleTd);
		tableRow.appendChild(inputTd);
		//add the row after the current one
		referenceNode = document.getElementById('imgRow'+curImgRow);
		insertAfter(referenceNode, tableRow);
		curImgRow++;
	}
}

/* toggle property image edit/replace inputs */

function toggleRep(field){
	var imageId = field.id.substring(11);
	if(field.checked){
		document.getElementById('delImg'+imageId).disabled = true;
		document.getElementById('repImgInput'+imageId).style.display = 'block';
	}else{
		document.getElementById('delImg'+imageId).disabled = false;
		document.getElementById('repImgInput'+imageId).style.display = 'none';
	}
}

function toggleDel(field){
	var imageId = field.id.substring(6);
	if(field.checked){
		document.getElementById('repImgChkbx'+imageId).disabled = true;
	}else{
		document.getElementById('repImgChkbx'+imageId).disabled = false;
	}
}

function buildWorkingBox(displayText){
 	var containerDiv = document.createElement('div');
	containerDiv.setAttribute('id', 'feedbackPopupEnquiry');
	var titleDiv = document.createElement('div');
	titleDiv.setAttribute('class', 'divTitle');
	titleDiv.setAttribute('id', 'divTitle');
	var titleMsg = document.createTextNode(displayText);
	var contentDiv = document.createElement('div');
	contentDiv.setAttribute('class', 'feedbackContent');
	var messageP = document.createElement('p');
	messageP.setAttribute('class', 'center');
	messageP.setAttribute('id', 'feedbackMessageContainer');
	var animGif = document.createElement('img');
	animGif.setAttribute('src', 'http://www.mintlocation.com/img/green_rot.gif');
	var breakTag = document.createElement('br');
	var waitText = document.createTextNode('(Please wait...)');
	
	messageP.appendChild(animGif);
	messageP.appendChild(breakTag);
	messageP.appendChild(waitText);
	contentDiv.appendChild(messageP);
	titleDiv.appendChild(titleMsg);
	containerDiv.appendChild(titleDiv);
	containerDiv.appendChild(contentDiv);
	document.getElementById("feedbackHolder").appendChild(containerDiv);
 }
