// IE 6 FIX
ie = document.all;
if(ie) {
   try {
		document.execCommand("BackgroundImageCache", false, true);
   } catch(err) {}
}


var timerID = null 
var timerRunning = false 

function stopclock(){ 
    if(timerRunning) 
        clearTimeout(timerID) 
    timerRunning = false 
}

function in_array(a){
	var o = {};
	for(var i=0; i<a.length; i++){
		o[a[i]]='';
	}
	return o;
}

function startclock(){ 
    stopclock() 
    showtime() 
}

function showtime(){ 
    var now = new Date() 
    var hours = now.getHours() 
    var minutes = now.getMinutes() 
    var seconds = now.getSeconds() 
    var timeValue = hours 
    timeValue  += ((minutes < 10) ? ":0" : ":") + minutes 
    timeValue  += ((seconds < 10) ? ":0" : ":") + seconds 
    document.getElementById('clock').firstChild.nodeValue = timeValue 
    timerID = setTimeout("showtime()",1000) 
    timerRunning = true 
} 

function isUndefined(a) {
    return typeof a == 'undefined';
}

function selections_validate(deliverto, totalcount) {
    var checkbox_choices = 0;

    for (counter = 0; counter < totalcount; counter++) {
        var elem = 'chk'+(counter+1);
        if (document.selections.elements[elem].checked) {
            checkbox_choices = checkbox_choices + 1;
        }
    }

    if (checkbox_choices < 1) {
        alert("Please tick at least one item from the list below.");
    } else {
        document.selections.action = deliverto;
        document.selections.submit();
    }
}

function selections_validate_del(deliverto, totalcount) {
    var checkbox_choices = 0;

    for (counter = 0; counter < totalcount; counter++) {
        var elem = 'chk'+(counter+1);
        if (document.selections.elements[elem].checked) {
            checkbox_choices = checkbox_choices + 1;
        }
    }

    if (checkbox_choices < 1) {
        alert("Please tick at least one item from the list below.");
    } else {
        if (confirm('Are you sure you want to delete all selected items.\nPLEASE NOTE: Any related items may be deleted!')) {
            document.selections.action = deliverto;
            document.selections.submit();
        }
    }
}

function pfv(deliverto, getvars) {
    link = deliverto+'?'+getvars
    MM_openBrWindow(link, '', '');
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
    window.open(theURL,winName,features);
}

function selectAll(theform, thecheckbox) {
	for(var i=0; i<5000; i++) {
		if (document.selections.elements['chk'+i]) {
			document.selections.elements['chk'+i].checked = true;
	   }
	}
}

function dselectAll() {
   for(var i=0; i<5000; i++) {
      if (document.selections.elements['chk'+i]) {
         document.selections.elements['chk'+i].checked = false;
      }
   }
}

function checkBox(themouseevent, box, i, theclass) {
	selected_row_style = "selected";
	x = 'tr' + i;
	if(themouseevent=="click") {
		if(box.checked==true) { 
			box.checked = false;
			document.getElementById(x).className =  theclass;
		} else { 
			box.checked = true;
			document.getElementById(x).className =  selected_row_style;
		}
	} else if(themouseevent=="over") {
		if(box.checked==false) document.getElementById(x).className =  theclass;
	} else if(themouseevent=="out") {
		(box.checked==false) ? document.getElementById(x).className =  theclass : document.getElementById(x).className =  selected_row_style;
	} else if(themouseevent=="selectAll") {
		for(var n=0; n<5000; n++) {
			thebox = box + n;
			if(document.getElementById(thebox)) {
				document.getElementById(thebox).checked = true;
				x = 'tr' + n;
				document.getElementById(x).className = selected_row_style;
			}
		}
	}  else if(themouseevent=="dselectAll") {
		for(var n=0; n<5000; n++) {
			thebox = box + n;
			if(document.getElementById(thebox)) {
				document.getElementById(thebox).checked = false;
				x = 'tr' + n;
				(n%2==0) ? theclass = "row" : theclass = "alt";
				document.getElementById(x).className =  theclass;
			}
		}
	}	
}

document.getElementsByClassName = function(cl) {
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = this.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
}

function set_required_fields(arr){
   for (i=0; i<arr.length; i++){
      e = $('#' + arr[i]).parent().children('label')
      e.addClass('required');
   }
}

function alternateRows(){
	el = document.getElementsByTagName("ol");
	cls_name = ""
	for (i=0; i<el.length; i++){
		rows = el[i].getElementsByTagName("label");
		for (j=0; j<rows.length; j++){
			x = j % 2
			if (x != 0){
				rows[j].parentNode.className = cls_name + "alt";
			}
		}
	}
}

function limit_text(limitSpan, limitCount, limitNum){
	if ($(limitCount).val().length > limitNum){
		$(limitCount).val($(limitCount).val().substring(0, limitNum));
	}
	else{
		$(limitSpan).html(limitNum - $(limitCount).val().length);
	}
}

function s_h_agent(){
	if($('#id_type').val() == 'Estate Agent'){
		$('.agent_form').show()
	}
	else{
		$('.agent_form').hide()
	}
}

function s_h_let(){
	if($('#id_listing_type').val() == 'To Let'){
		$('#id_lease_period').parent().show();
		$('#id_occupation_date').parent().show();
	}
	else{
		$('#id_lease_period').parent().hide();
		$('#id_occupation_date').parent().hide();
	}
}

function s_h_type(){
	if($('#id_division_type').val() == 'Residential'){
		$('.resextra_form').show()
		$('.commextra_form').hide()
		$('.documents_form').hide()
		$('#id_listing_type option[value="To Let"]').show()
		$('#id_development_logo').parent().parent().hide()
	}
	else if($('#id_division_type').val() == 'Commercial'){
		$('.commextra_form').show()
		$('.resextra_form').hide()
		$('.documents_form').hide()
		$('#id_listing_type option[value="To Let"]').show()
		$('#id_development_logo').parent().parent().hide()
	}
	else if($('#id_division_type').val() == 'Development'){
		$('.documents_form').show()
		$('#id_development_logo').parent().parent().show()
		$('.commextra_form').hide()
		$('.resextra_form').hide()
		$("#id_document_num").val(count_forms())
		$('#id_listing_type option[value="To Let"]').hide()
	}
	else{
		$('.commextra_form').hide()
		$('.resextra_form').hide()
		$('.documents_form').hide()
		$('#id_development_logo').parent().parent().hide()
	}
}

function s_h_parkings(value){
	if(value > 10){
		$('#id_parkings_txt').show();
		$('#id_parkings_txt').val(value);
		$('#id_parkings').hide();
		$("#id_parkings_link").text('Cancel')
	}
}

function toggle_logo(mode){
	
	if(mode == 'cancel'){
		$('#id_agency_logo').parent().parent().hide()
		$('#id_predefined_logo').parent().show()
		$('#id_predefined_logo').parent().removeClass('alt')
	}
	else{
		$('#id_predefined_logo').parent().hide()
		$('#id_agency_logo').parent().parent().show()
		$('#imgdel_show1').show()
	}
}

function set_province(val_arr, sel_opt){
	options = '<option value="">---------</option>'
	for(var i=0; i<val_arr.length; i++){
		options += '<optgroup label="' + val_arr[i][0] +'">'
		opts = val_arr[i][1]
		for(var x=0; x<opts.length; x++){
			if(sel_opt == opts[x][1]){
				options += '<option value="' + opts[x][0] +'" selected="selected">' + opts[x][1] + '</option>'
			}
			else{
				options += '<option value="' + opts[x][0] +'">' + opts[x][1] + '</option>'
			}
		}
		options += '</optgroup>'
    }
    $("#id_region").html(options);
}

function set_proptype(val_arr, sel_opt){
	options = '<option value="">---------</option>'
	for(var x=0; x<val_arr.length; x++){
		if(sel_opt == val_arr[x]){
			options += '<option value="' + val_arr[x] +'" selected="selected">' + val_arr[x] + '</option>'
		}
		else{
			options += '<option value="' + val_arr[x] +'">' + val_arr[x] + '</option>'
		}
	}
    $("#id_property_type").html(options);
}

function add_new_option(box) {
	select_box = '#id_' + box ;
	input_box = select_box + '_txt';
	link = '#id_' + box + '_link';
	
	if ($(select_box).is(':visible')) {
		$(select_box).hide();
		$(input_box).show()
		$(link).html('Cancel');
	} else {
		$(select_box).show();
		$(input_box).hide();
		$(link).html('Add New');
	}
}


function to_decimal(float_value, decimal_places){
	if(isNaN(float_value)){
		return ''
	}
	if(decimal_places == ''){
		decimal_places = 2
	}
	decimal_places = parseInt(decimal_places)
	float_value = parseFloat(float_value)
	return_value = float_value.toFixed(decimal_places)
	
	if(return_value == 'Infinity'){
		return 0
	}
	else{
		return return_value;
	}
}

function count_forms(){
	return $ol_elements = $("#id_document_form").children("div").length
}

function limit_text_init(next_num){
	$('#id_'+next_num+'-doc_description').parent().after('<li><label>&nbsp;</label><strong><span id="id_txt_counter'+next_num+'" style="font-weight:bold">70</span> / 70</strong> characters remaining</li>')
	$('#id_'+next_num+'-doc_description').keypress(function(){
		limit_text('#id_txt_counter'+next_num+'', '#id_'+next_num+'-doc_description', 70);
	});
	$('#id_'+next_num+'-doc_description').blur(function(){
		limit_text('#id_txt_counter'+next_num+'', '#id_'+next_num+'-doc_description', 70);
	});
	limit_text('#id_txt_counter'+next_num+'', '#id_'+next_num+'-doc_description', 70);
	alternateRows()
}

function add_new_document(current_num){
	var next_num = current_num + 1
	var new_html = '<div id="id_document%s"><ol><h3>Document %s</h3><li><label for="id_%s-doc_name">Document title:</label><input id="id_%s-doc_name" name="%s-doc_name" type="text" value=""/></li><li><label for="id_%s-doc_description">Document description:</label><textarea id="id_%s-doc_description" name="%s-doc_description" cols="40" rows="10"></textarea></li><li><label for="id_%s-doc_file">File Upload:</label><input id="id_%s-doc_file" name="%s-doc_file" type="file"/></li><li id="id_doc_control%s"><label>&nbsp;</label><a href="#1" onclick="add_new_document(%s, false)">Add Another Document</a> &nbsp; | &nbsp; <a href="#1" onclick="remove_document(%s)">Remove This Document</a></li></ol></div>'
	if(count_forms() == 0){
		$("#id_document_num").after(new_html.replace(/%s/g, current_num))
	}
	else if(count_forms() < 9){
		$("#id_document"+current_num).after(new_html.replace(/%s/g, next_num))
		$("#id_doc_control"+current_num).html('</ol></div>')
		$("#id_document_num").val(count_forms())
	}
	else if(count_forms() == 9){
		new_html += '</ol></div>'
		$("#id_document"+current_num).after(new_html.replace(/%s/g, next_num))
		$("#id_doc_control"+current_num).html('')
		$("#id_doc_control"+next_num).html('<label>&nbsp;</label><a href="#1" onclick="remove_document(10)">Remove This Document</a>')
		$("#id_document_num").val(count_forms())
	}
	limit_text_init(next_num)
}


function remove_document(current_num){
	var prev_num = current_num - 1
	var num_ele = count_forms()
	var app_html = '<label>&nbsp;</label><a href="#1" onclick="add_new_document(%s, false)">Add Another Document</a> &nbsp; | &nbsp; <a href="#1" onclick="remove_document(%s)">Remove This Document</a>'
	$("#id_document"+current_num).remove()
	if(num_ele == 1 && current_num == 1){
		add_new_document(1)
		$("#id_document_num").val(count_forms())
	}
	else{
		$("#id_document_num").val(count_forms())
	}
	$("#id_doc_control"+prev_num).html(app_html.replace(/%s/g, prev_num))
	limit_text_init(current_num)
}

