// 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++;
        }
    }

    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 ' + checkbox_choices +' 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(){
	var ele_array = $('li:visible');
	$.each($(ele_array).children('label'), function(i, val){
		d = i % 2;
		if(d != 0){
			$(val).parent().addClass('alt');
		}
		else{
			$(val).parent().removeClass('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()
	}
    alternateRows()
}

function s_h_listing_type(){
    
    $('#id_lease_period').parent().hide()
    $('#id_occupation_date').parent().hide()
    $('.fractionalextra_form').hide()
    $('.auctionextra_form').hide()
    $('.holidayextra_form').hide()
    
	if($('#id_listing_type').val() == 'To Let'){
		$('#id_lease_period').parent().show()
		$('#id_occupation_date').parent().show()
	}
	else if($('#id_listing_type').val() == 'Fractional Ownership'){
        $('.fractionalextra_form').show()
	}
	else if($('#id_listing_type').val() == 'Auction'){
        $('.auctionextra_form').show()
	}
	else if($('#id_listing_type').val() == 'Holiday Letting'){
        $('.holidayextra_form').show()
	}
    alternateRows()
}

function s_h_type(){
    
    $('.commextra_form').hide()
    $('.resextra_form').hide()
    $('.documents_form').hide()
    $('#id_development_logo').parent().parent().hide()
    $('#id_listing_type option[value="To Let"]').hide()
    $('#id_listing_type option[value="Fractional Ownership"]').hide()
    $('#id_listing_type option[value="Holiday Letting"]').hide()
    $('#id_listing_type option[value="Auction"]').hide()
    
	if($('#id_division_type').val() == 'Residential'){
		$('.resextra_form').show()
		$('#id_listing_type option[value="To Let"]').show()
		$('#id_listing_type option[value="Fractional Ownership"]').show()
		$('#id_listing_type option[value="Auction"]').show()
		$('#id_listing_type option[value="Holiday Letting"]').show()
	}
	else if($('#id_division_type').val() == 'Commercial'){
		$('.commextra_form').show()
		$('#id_listing_type option[value="To Let"]').show()
		$('#id_listing_type option[value="Auction"]').show()
	}
	else if($('#id_division_type').val() == 'Development'){
		$('.documents_form').show()
		$('#id_development_logo').parent().parent().show()
		$("#id_document_num").val(count_forms())
	}
    s_h_listing_type()
    alternateRows()
}

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_hide1').hide()
		$('#imgdel_show1').show()
	}
}

function set_province(val_arr, sel_opt){
    options = '<option value="">loading...</option>'
    $("#id_region").html(options);
	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)
}

function embedObject(s, c){
    var color = '#FFFFFF'
    if(c){
        color = '#DFE2E7'
    }
	var newHtml = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="400" height="22" id="uploadBitmap_' + s + '">';
	newHtml += '<param name="allowScriptAccess" value="sameDomain" />';
	newHtml += '<param name="allowFullScreen" value="false" />';
	newHtml += '<param name="movie" value="/assets/fla/uploadBitmap.swf?seq='+s+'" />';
	newHtml += '<param name="quality" value="high" />';
	newHtml += '<embed src="/assets/fla/uploadBitmap.swf?seq='+s+'" quality="high" bgcolor="'+color+'" width="400" height="22" name="uploadBitmap" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />';
	newHtml += '</object>';
    return newHtml;
}

function getFileName(s, img){
    $('#id_image' + s).val(img);
}

function getFlashVersion(){ 
    try { 
        try {
            var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
            try { axo.AllowScriptAccess = 'always'; } 
            catch(e) { return '6,0,0'; } 
        } catch(e) {} 
        return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; 
    } catch(e) { 
        try { 
            if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){ 
                return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; 
            }
        } catch(e) {}
    } 
    return '0,0,0'; 
}

function s_h_ad_option(){
    if($('#id_listing_option').val() == 'Featured Listing'){
        $('#id_advertising_option').parent().show()
    }
    else{
        $('#id_advertising_option').parent().hide()
    }
    alternateRows()
}

function s_h_listing_option() {
    if ($('#id_listing_option').val() == 'Featured Listing') {
        $('#id_listing_position').parent().show();
        $('#id_advertising_option').parent().show();
        $('#id_start_date').parent().show();
    } else {
        $('#id_listing_position').parent().hide();
        $('#id_advertising_option').parent().hide();
        $('#id_start_date').parent().hide();
    }
    alternateRows();
}

function s_h_ad_options(){
    if ($('#id_listing_position').val() == 'Homepage') {
        // Homepage options: 1w, 2w, 3w, 4w
        $("#id_advertising_option option:contains('Week')").each(function() { $(this).show(); });
        $("#id_advertising_option option:contains('Month')").each(function() { $(this).hide(); });
        $("#id_advertising_option").val("");
    } else if ($('#id_listing_position').val() == 'Search Results') {
        // Search Results options: 1m, 2m, 3m, 4m
        $("#id_advertising_option option:contains('Month')").each(function() { $(this).show(); });
        $("#id_advertising_option option:contains('Week')").each(function() { $(this).hide(); });
        $("#id_advertising_option").val("");
    }
}

