function isArray(v) {
	return v && typeof v === 'object' && typeof v.length === 'number' && !(v.propertyIsEnumerable('length'));
}

function getButton(name, caption, action, width) {
	return "<div class=\"buttons\"><input class=\"btnredsmall\" type=\"submit\" name=\"" + name + "\" id=\"" + name + "\" value=\"" + caption + "\"" + 
		" style=\" width:" + width + "px;\" " +
		(action != null ? "onclick=\"" + action + "\"" : '') + " /><div class=\"btnredsmallEnding\"></div></div>";
}

function getDialogHTML(w, h, title, content, buttons, close_btn) {
	var html = '<table border="0" cellpadding="0" cellspacing="0" id="dialogtable" style="z-index: 9999; width=auto"><tbody><tr><td class="popup_shadow popup_top_left"><div class="popup_background"><table cellspacing="0" cellpadding="0" class="dialogtable" width="' + w + '" height="' + h + '"><tr><td class="dialogtitle" height="40" width="' + (w - 16) + '">' + title + '</td>';
		
	if (close_btn) html += '<td class="dialogtitle" style="height:30px; width:10px; vertical-align:top; text-align:right"><a href="javascript:closeDialog();"><b>X</b></a></td>';

	var neg = 80;	
	if (buttons != null && buttons != '') neg = 140;
	
	html +=	'</tr><tr><td class="dialogcontent" colspan="2" id="dialogcontent">' + content + '</td></tr>';
		
	if (buttons != null && buttons != '') {
		var buttontable = '<table class="dialogtable" style="margin: 0 auto;" height="30px"><tr>';
		for (var i=0; i < buttons.length; i++) {
			if (i > 0) buttontable = buttontable + '<td width="60">&nbsp;</td>';
			buttontable = buttontable + '<td>' + buttons[i] + '</td>';
		}
		buttontable += '</tr></table>';
		html += '<tr><td class="dialogbottom" colspan="2">' + buttontable + '</td></tr>';
	}
	html += '</table></div></td><td class="popup_shadow popup_top_right">&nbsp;</td></tr><tr><td class="popup_shadow popup_bottom_left">&nbsp;</td><td class="popup_shadow popup_bottom_right">&nbsp;</td></tr></tbody></table>';
	
	return html;
}

function getAdvertisementHTML(w, h, title, content, buttons, close_btn) {
	var html = '<table border="0" cellpadding="0" cellspacing="0" id="dialogtable" style="z-index: 9999; width=auto"><tbody><tr><td class="popup_shadow popup_top_left"><div class="popup_background"><table cellspacing="0" cellpadding="0" class="dialogtable" width="' + w + '" height="' + h + '"><tr><td class="dialogtitle" height="40" width="' + (w - 16) + '">' + title + '</td>';
		
	if (close_btn) html += '<td class="dialogtitle" style="height:30px; width:10px; vertical-align:top; text-align:right"><a href="javascript:closeDialog();">X</a></td>';

	var neg = 80;	
	if (buttons != null && buttons != '') neg = 140;
	
	html +=	'</tr><tr><td class="dialogcontent" colspan="2" id="dialogcontent" style="padding:5px !important">' + content + '</td></tr>';
		
	if (buttons != null && buttons != '') {
		var buttontable = '<table class="dialogtable" style="margin: 0 auto;" height="30px"><tr>';
		for (var i=0; i < buttons.length; i++) {
			if (i > 0) buttontable = buttontable + '<td width="60">&nbsp;</td>';
			buttontable = buttontable + '<td>' + buttons[i] + '</td>';
		}
		buttontable += '</tr></table>';
		html += '<tr><td class="dialogbottom" colspan="2">' + buttontable + '</td></tr>';
	}
	html += '</table></div></td><td class="popup_shadow popup_top_right">&nbsp;</td></tr><tr><td class="popup_shadow popup_bottom_left">&nbsp;</td><td class="popup_shadow popup_bottom_right">&nbsp;</td></tr></tbody></table>';
	
	return html;
}


function openDialog(w, h, title, content, buttons, close_btn) {
	if ($('#pg_dialog')[0] == null) $('<div id="pg_dialog" style="display:none; cursor: default"></div>').appendTo('body');
	$.extend($.blockUI.defaults.overlayCSS, { opacity:0.2 });
	$.extend($.blockUI.defaults.css, {backgroundColor: "transparent"});
	$.blockUI.defaults.fadeIn = 0;
	$.blockUI({ message: $('#pg_dialog'), css: {border: '0px solid #333', width: w + 'px', height: h + 'px', margin:'-' + ((h+50)/2) + 'px 0 0 -' + ((w+40)/2) + 'px', top:'50%', left:'50%'} });
	
	if (content != null && content != '') {
        $('#pg_dialog').html(getDialogHTML(w, h, title, content, buttons, close_btn));
		$('#mediadisplay embed, #mediadisplay object, #mediadisplay iframe').hide();
	}
}

function loadDialog(w, h, title, url, buttons, close_btn, recenter) {
	if(close_btn==null) close_btn = true;
	openDialog(w, h, title, '<h3 style="margin-top:' + ((h-100)/2) + 'px">'+gettext("Please wait...")+'</h3></div>', null);
    $.get(url,
        function(data) {   
            // unblock when remote call returns            
            $('#pg_dialog').html(getDialogHTML(w, h, title, data, buttons, close_btn));
            if (recenter != false) {
            	recenterDialog();
            }
        });        
}

function recenterDialog() {
    // re-center dialog
    var new_height = $('#pg_dialog').height();
    var new_width = $('#pg_dialog').width();
    $('.blockUI.blockMsg').css({'margin': '-' + ((new_height)/2) + 'px 0 0 -' + ((new_width+40)/2) + 'px', 'top': '50%', 'left': '50%'});
}

function loadAdvertisement(w, h, title, url) {
	openDialog(w, h, title, '<h3>Please wait...</h3>', null);

	$.get(url,
        function(data) {   
            // unblock when remote call returns            
            $('#pg_dialog').html(getAdvertisementHTML(w, h, title, data, null, true));
        });
        
}

function openImageDialog(w, h, image, caption_id) {
	openDialog(w, h, "", '<img src="'+image+'" />', null, true);
	if (typeof caption_id != 'undefined') {
		$('#'+caption_id).clone().prependTo($('#dialogcontent')).show();
	}
}

function openFloorPlanImageDialog(w, h, image, caption_id, title) {
	openDialog(w, h, title, '<img src="'+image+'" />', null, true);
	if (typeof caption_id != 'undefined') {
		$('#'+caption_id).clone().prependTo($('#dialogcontent')).show();
	}
}

/*
function openFloorplanDialog(w, h, image, image_previous, image_next2, caption_id) {
	
	var image_prev 	= '<img name=\"floorplan_image_preview\" src=\"'+image_previous+'\" />';
	var image_next 	= '<img name=\"floorplan_image_preview\" src=\"'+image_next2+'\" />';
	
	var action1    	= 'document.getElementById(\"floorplan_image_preview_div\").innerHTML = \"'+image_prev+'\"';
	var action2    	= 'document.getElementById(\"floorplan_image_preview_div\").innerHTML = \"'+image_next+'\"';
	action1="document.getElementById(\'floorplan_image_preview_div\').innerHTML = \'1\'";	
	action2="document.getElementById(\'floorplan_image_preview_div\').innerHTML = \'2\'";
	action1 = "";
	action2 = "";
		
	//var content 	= "<input onClick='"+action1+"' type='submit' value=' < Prev' name='Prev'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+"<input onClick='"+action2+"' type='submit' value='Next >' name='Next'>";

	var content 	= "<input type='submit' value=' < Prev' name='Prev'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+"<input type='submit' value='Next >' name='Next'>";
	
	var final_content = "<img name='floorplan_image_preview' src='"+image+"' /><br />"+content;
	
	final_content 	= "<div name='floorplan_image_preview_div'>" + final_content + "</div>" ;	
	openDialog(w, h, "", final_content, null, true);
	if (typeof caption_id != 'undefined') {
		$('#'+caption_id).clone().prependTo($('#dialogcontent')).show();
	}
}
*/

function openMovieDialog(w,h,video,type){
	if(type=="htm"){
		openDialog(w, h, "", video,null,true);
	}
	//openDialog(w, h, "", '<embed height="550" width="550" allowfullscreen="true" allowscriptaccess="always" quality="high" name="mpl" id="mpl" style="" src="http://i2.propertyguru.com.sg/vtours/thumb/9/3/e/3/93e34d548001_1_V550.swf" type="application/x-shockwave-flash"/>',null,true);
}


function submitDialogForm(form_id) {
    $(form_id).ajaxSubmit({target: '#dialogcontent', beforeSubmit:preSubmit, success:formResult});     
    return false; 
}

function preSubmit() {
	$('#dialogcontent').html('<h3>Please wait...</h3>');
	return true;
}

function formResult() {
	recenterDialog();	
}

function openMessageBox(title, message) {	
	openDialog(300, 200, title, message,
		new Array(getButton('btn_ok', 'ok', 'closeDialog();', 60)), true);
}

function openBigMessageBox(width,height,title, message) {	
	openDialog(width, height, title, message,
		new Array(getButton('btn_ok', 'ok', 'closeDialog();', 60)), true);
}

function busyDialog(title) {
	var html = "Please wait ...<br/><br/><img src=\"/images/busy.gif\"/><br /><div class='floatright'><a href='javascript:closeDialog()'>[cancel]</a></div>";
	openDialog(200, 150, title, html, '', false); 
}

function errorDialog(message) {
	openDialog(300, 150, "ERROR ENCOUNTERED", message,
		new Array(getButton('btn_ok', 'ok', 'closeDialog();', 60)), true);
}

function closeDialog() {
	$.unblockUI();
	$('#pg_dialog').remove();
	$('#mediadisplay embed, #mediadisplay object, #mediadisplay iframe').show();
}

function getRadioValue(formName, radioInputName) {
	var f = document.forms[formName];
	if (f) {
		f = f.elements[radioInputName];
	}
	if (f) {
		if (typeof f.length == 'undefined') {
			f = [f];
		}
		for (var i = 0; i < f.length; i++) {
			if (f[i].checked) {
				return f[i].value;
			}
		}
	}

	return null;
}

function addShortlist(listing_id) {
	busyDialog(gettext("Adding to Shortlist"));

	var url = "/ps_xmlhttp_addshortlist?id=" + listing_id;
    $.getJSON(url, function(data) {
	    $('#shortlist_count').html(data.size).show();
	    $('#shortlist_btn_'+listing_id).html(gettext("Shortlisted")).addClass('greybold');
	    closeDialog();
	    
	    // Encourage log-in or registration:
	    if (!data.logged && data.size == 1) {
	    	var content = "<div class='top10' style='width:100%; text-align:left'>"+gettext("Please")+" <a href=\"javascript:openLoginDialog('/shortlist')\" class='bluelink'>"+gettext("login")+"</a> " + 
	    				  gettext("if you want your shortlist to be saved for future visits")+".<br><br>" +
	    				  gettext("Not a ") + (REGION == 'MY' ? "HomeGuru" : "PropertyGuru") + gettext(" Member yet?")+ "<a href=\"javascript:openRegisterDialog('/shortlist')\" class='bluelink'>"+gettext("Register now")+"</a> " + 
	    				  gettext("so you don't lose your shortlist once you close your browser")+".</div>"; 
	    	var buttons = ["<div class='buttons'><input type='button' name='close' value='CLOSE' class='btnredsmall' onclick='closeDialog()' /><div class='btnredsmallEnding'/></div>"];
	    	
	    	openDialog(350, 200, gettext("Tip for Shortlisting"), content, buttons, 1);
	    }
    });
}

function offensive(content_id) {
	
	busyDialog("Submitting your Report");
	$.ajax({  
         	type: "POST",  
			url: "/ps_project_review?id=" + content_id + "&reportOffensive=true",  
        	 async: true,
          	 success: function(msg){  
          	 	$('#reportOffensive_'+content_id).html(gettext("<b>Your report has been submitted successfully.</b>"));
         
         		closeDialog();
         	}  
       	});
	
	 
}

var popup_current_data = null;
function listPopup(instructions, data, id_col, show_columns, callback, formatitem) {
	popup_current_data = data;

	var html = '<p class="alignleft left10 bottom10">' + instructions + '</p><form name="popup_form"><fieldset><div style="width:660px;margin:0 auto;height:320px;overflow-y:auto;overflow-x:hidden"><table class="table1" style="width:100%">';
 	$.each(data, function(i, item) {
 			var alt = '';
 			if (i % 2) alt = ' class="alt"';
 			html = html + '<tr><td'+alt+'><input type="radio" id="popup_id_' + i + '" name="popup_id" value="' + i + '"/></td>';
 			for (var x = 0; x < show_columns.length; x++) {
 				html = html + '<td'+alt+'>';
 				if(typeof formatitem != 'undefined' && x == 0){
 					html = html + '<label style="padding:0" for="popup_id_' + i + '">' + formatitem(item[show_columns[x]]) + '</label>';
 				}else if (item[show_columns[x]] != null) {
 					html = html + '<label style="padding:0" for="popup_id_' + i + '">' + item[show_columns[x]] + '</label>';
 				}
 				html = html + '</td>';
 			}
 			html = html + '</tr>'; 			
        });	
	html = html + '</table></div><fieldset></form>';

	var buttons = [getButton('popup_select', 'Select', null, 120), getButton('popup_none', 'Cancel', null, 120)];	

	openDialog(700, 420, 'Search Results', html, buttons, true);
	
	$('#popup_select').click(function() {
			var i = getRadioValue('popup_form', 'popup_id');
			closeDialog();
			callback(popup_current_data[i]);
		});

	$('#popup_none').click(function() {
			closeDialog();
			callback('N/A');
		});

}

function help(help_id) {
	loadDialog(500, 400, '<img src="/images/icons/help.png"/>&nbsp;Help', '/ps_dialog_help?id='+help_id);
}

function truncate(text, length) {
	return (text.length <= length) ? text : text.substr(0,length-3) + "...";
}

function cancelProp(e) {
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function forceNumber(id) {
	
	// REQUIRES jquery.caret.js
	
	$(id).keyup(function(e) {
		var startPos = $(id).caret().start;
		var startLength = $(id).val().length;
		$(id).val(formatNumber($(id).val().replace(/[^\d]/g,'')));
		if (startLength == $(id).val().length) $(id).caret({start : startPos, end : startPos});
		else $(id).caret({start : startPos + ($(id).val().length - startLength), end : startPos + ($(id).val().length - startLength)});
	});
	
	$(id).blur(function(e) {
		$(id).val(formatNumber($(id).val().replace(/[^\d]/g,'')));
	});

	// the code below is shockingly bad usability

	/* $(id).keypress(function(e) { // only allow numbers in price field	
		if (e.which == 0) return true;
		else if (e.which >= 48 && e.which <= 57) {
			var c = String.fromCharCode(e.which);			
			var v = $(id).val() + c;
			$(id).val(formatNumber(v));			
		}		
		return false;
	});
		
	$(id).keydown(function(e) {
		if (e.which == 8) { // backspace
			var v = $(id).val();
			v = v.substring(0, v.length - 1);
			$(id).val(formatNumber(v));
			return false;
		}
	}); */
}

function formatNumber(nro) {
	var v = nro;
	while (v.indexOf(',') >= 0) { // remove all commas
		v = v.replace(',','');
	}
	
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(v)) {
		v = v.replace(rgx, '$1' + ',' + '$2');		
	}
	
	return v;
}

function openLoginDialog(redirect) {
	if (REGION == 'MY') loadDialog(550,300,'Login to HomeGuru.com.my','/login-dialog?redirect='+escape(redirect));
	else loadDialog(550,300,gettext("Login to PropertyGuru.com.sg"),'/login-dialog?redirect='+escape(redirect));
}

function openCgLoginDialog(redirect) {
	loadDialog(550,300,gettext("Login to CommercialGuru.com.sg"),'/login-dialog?redirect='+escape(redirect));
}
function openRegisterDialog(redirect) {
	closeDialog(); // to re-center in window
	if (REGION == 'MY') loadDialog(550,525,'Register with HomeGuru.com.my','/register-dialog?redirect='+escape(redirect));
	else loadDialog(550,525,gettext("Register with PropertyGuru.com.sg"),'/register-dialog?redirect='+escape(redirect));
}

function openCgRegisterDialog(redirect) {
	closeDialog(); // to re-center in window
	loadDialog(550,525,'Register with CommercialGuru.com.sg','/register-dialog?redirect='+escape(redirect));
}

function changeItemsPerPage() {
	var value = $('#items_per_page').val();
	var query = changeParameter('items_per_page', value);
	document.location.search = query;
}

function changeSortOrder() {
	var index = document.getElementById('quicksort').selectedIndex;
	var sortvalue = document.getElementById('quicksort').value;
	var ordervalue = document.getElementById('quicksort').options[index].getAttribute('name');
	var query;
	
	query = changeParameter('sort', sortvalue);
	query = changeParameter('order', ordervalue, query);
	document.location.search = query;
}

function changeParameter(key, value, query) {
	var sch;
	if (typeof query == 'undefined') sch = document.location.search;
	else sch = query;
	var param = key + '=' + value;
	if (!sch.length) sch = '?' + param;
	else {
		var replaceregex = new RegExp(key + '=[^&]*');
		if(replaceregex.test(sch))
			sch = sch.replace(replaceregex, param);
		else
			sch += '&' + param;
	}
	return sch;
}

function submit_filter(qstring) {
	var param = qstring.split('=')[0];
	var replaceregex = new RegExp(param + "=[^&]*");
	var sch = document.location.search;
	if (!sch.length) sch = '?' + qstring;
	else {
		if(replaceregex.test(sch))
			sch = sch.replace(replaceregex, qstring);
		else
			sch += '&' + qstring;
	}
	document.location.search = sch;
}

this.tooltip = function() {
	/* CONFIG */
	xOffset = 10;
	yOffset = 20;
	// these 2 variable determine popup's distance from the cursor
	// you might want to adjust to get the right result
	/* END CONFIG */
	$("a.tooltip").hover(function(e) {
		this.t = this.title;
		this.title = "";
		$("body").append("<p id='tooltip'>" + this.t + "</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
	},
	function() {
		this.title = this.t;
		$("#tooltip").remove();
	});
	$("a.tooltip").mousemove(function(e) {
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};

$(document).ready(function() {
	// change to class instead of ID if we need multiple controls per page
	$('#items_per_page').change(function() { changeItemsPerPage(); });
	$('#quicksort').change(function() { changeSortOrder(); });
});

// Handle ENTER button presses to simulate a submit forms with many submit buttons
$(function() {
	$("form input").keypress(function (e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$('input[type=submit].defaultSubmitOnEnter').click();
			return false;
		} else {
			return true;
		}
	});
});
