function checkSearchKeyword(object)
{
  if (object.PropertyKeyword.value.length < 2)
  {
    alert(trans.two_characters_needed);

    return false;
  } // end if

  return true;
} // end function

function getId(id)
{
  return document.getElementById(id);
} // end function

function switchSubmit()
{
	if (getId('AddressPostcode').value.length > 3)
	{
		getId('AddSubmit').disabled = false;
	}
	else
	{
		getId('AddSubmit').disabled = true;
	} // end if
} // end function

function switchSubmit2()
{
	if (getId('PropertyRentalValue').value.length > 0)
	{
		getId('AddSubmit').disabled = false;
	}
	else
	{
		getId('AddSubmit').disabled = true;
	} // end if
} // end function

function property_mark(prop_id)
{
  if (getId('img_' + prop_id).value == 1)
  {
    getId('img_' + prop_id).value = 0;
    getId('div_img_' + prop_id).style.borderColor = '#dedfde';
    getId('p_img_' + prop_id).style.borderColor = '#dedfde';
  }
  else
  {
    getId('img_' + prop_id).value = 1;
    getId('div_img_' + prop_id).style.borderColor = '#900';
    getId('p_img_' + prop_id).style.borderColor = '#900';
  } // end if
} // end function








function trade_mark(prop_id)
{
  if (getId('img_' + prop_id).value == 1)
  {
    getId('img_' + prop_id).value = 0;
    getId('div_img_' + prop_id).style.borderColor = '#dedfde';
    getId('p_img_' + prop_id).style.borderColor = '#dedfde';
  }
  else
  {
    getId('img_' + prop_id).value = 1;
    getId('div_img_' + prop_id).style.borderColor = '#900';
    getId('p_img_' + prop_id).style.borderColor = '#900';
  } // end if
} // end function








function initToolTips()
{
  agt        = navigator.userAgent.toLowerCase();
  is_major    = parseInt(navigator.appVersion);
  is_minor     = parseFloat(navigator.appVersion);
  is_nav      = ((agt.indexOf('mozilla') != -1) && (agt.indexOf('spoofer') == -1)
                  && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera') == -1)
                  && (agt.indexOf('webtv') == -1) && (agt.indexOf('hotjava') == -1));
  is_nav4     = (is_nav && (is_major == 4));
  is_nav6     = (is_nav && (is_major == 5));
  is_nav6up     = (is_nav && (is_major >= 5));
  is_ie         = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));

  offsetX         = 0;
  offsetY         = 5;
  opacity         = 100;
  toolTipSTYLE    = 0;

  if (document.getElementById)
  {
    toolTipSTYLE = getId("toolTipLayer").style;
  } // end if

  if (is_ie || is_nav6up)
  {
    toolTipSTYLE.visibility = "visible";
    toolTipSTYLE.display     = "none";
    document.onmousemove     = moveToMousePos;
  } // end if
} // end function

function moveToMousePos(e)
{
  if (!is_ie)
  {
    x = e.pageX;
    y = e.pageY;
  }
  else
  {
    x = event.x + document.body.scrollLeft;
    y = event.y + document.body.scrollTop;
  } // end if

  toolTipSTYLE.left = 13 + x + offsetX + 'px';
  toolTipSTYLE.top  = y + offsetY + 'px';

  return true;
} // end function

function toolTip(msg)
{
  if (toolTip.arguments.length < 1)
  {
    if (is_nav4)
    {
        toolTipSTYLE.visibility = "hidden";
    }
    else
    {
        toolTipSTYLE.display = "none";
    } // end if
  }
  else // show
  {
    var content = '<table border="0" cellspacing="0" cellpadding="0" class="toolTip"><tr><td bgcolor="#777777">' +
                                  '<table border="0" cellspacing="1" cellpadding="0"<tr><td bgcolor="#ffffe5">'+
                                  '<font face="sans-serif" color="#017AC3">' + msg +
                                  '</font></td></tr></table>'+
                                  '</td></tr></table>';
    if (is_nav4)
    {
      toolTipSTYLE.document.write(content);
      toolTipSTYLE.document.close();
      toolTipSTYLE.visibility = "visible";
    }
    else if (is_ie || is_nav6up)
    {
      getId("toolTipLayer").innerHTML = content;
      toolTipSTYLE.display = 'block'
    } // end if
  } // end if
} // end function

function search(location_name, location_id)
{
  getId("PropertyKeyword").value     = location_name;
  getId("PropertyLocation").value    = location_id;
  getId("PropertySearchForm").submit();
} // end function

function checkLocation()
{
  if (getId("PropertyKeyword").value != getId("PropertyOldKeyword").value)
  {
    getId("RefineSearch").name = 'quick_search';
  } // end if
} // end function

function checkSearchKeywordRefine(object)
{
  if (object.PropertyKeyword.value.length < 2)
  {
    alert(trans.two_characters_needed);

    return false;
  } // end if

  checkLocation();
  return true;
} // end function

function autocompleteCallback (text, li)
{
    var s = text.value;
    var i = s.indexOf(' in ');
    if (i != -1)
        s = s.substr(0, i);
    text.value = s;
    if ($('PropertyOldKeyword'))
        $('PropertyOldKeyword').value = s;
    $('PropertyNewLocation').value = li.id.substr(16);
    //$('PropertySearchForm').submit();
}
function autocompleteBeforeSend(element, query)
{
  return query + '&data%5BProperty%5D%5Bcountry_code%5D=' + $('PropertyCountryCode')[$('PropertyCountryCode').selectedIndex].value;
}

function radiusUnitChange ()
{
    if ($('PropertyMapRadius'))
        $('PropertyMapRadius').value = "";
    if ($('PropertyMapUnit'))
        $('PropertyMapUnit').value = "";
    if ($('PropertyRadius'))
        $('PropertyRadius').removeClassName('disabled');
    if ($('PropertyUnit'))
        $('PropertyUnit').removeClassName('disabled');
}

function keywordChange ()
{
    radiusUnitChange();
    if ($('PropertyMapLatitude'))
        $('PropertyMapLatitude').value = "";
    if ($('PropertyMapLongitude'))
        $('PropertyMapLongitude').value = "";
    if ($('PropertyKeyword'))
        $('PropertyKeyword').removeClassName('disabled');
}

var mini_map = null;
var mini_map_marker = null;

function init_mini_map (lat, lng)
{
    mini_map = new google.maps.Map2($('mini_map'));
    mini_map.enableContinuousZoom();
    mini_map.enableScrollWheelZoom();
    mini_map.enableDoubleClickZoom();
    mini_map.addControl(new google.maps.SmallMapControl());
    mini_map.addControl(new google.maps.MapTypeControl());

    if (lat && lng) {
        mini_map.setCenter(new google.maps.LatLng(lat, lng), 13);
        mini_map_marker = new google.maps.Marker(new google.maps.LatLng(lat, lng), {draggable: true});
        mini_map.addOverlay(mini_map_marker);
    } else {
        mini_map.setCenter(new google.maps.LatLng(54.6865, -4.7461), 4);
        mini_map_marker = new google.maps.Marker(new google.maps.LatLng(54.6865, -4.7461), {draggable: true});
    }

    google.maps.Event.addListener(mini_map, 'click', function(overlay, latlng) {
            if (overlay instanceof google.maps.Marker) {
                mini_map.removeOverlay(overlay);
                $('PropertyLatitude').value = '';
                $('PropertyLongitude').value = '';
            } else {
                mini_map.removeOverlay(mini_map_marker);
                mini_map_marker.setLatLng(latlng);
                mini_map.addOverlay(mini_map_marker);
                $('PropertyLatitude').value = latlng.lat();
                $('PropertyLongitude').value = latlng.lng();
            }
        });
    google.maps.Event.addListener(mini_map_marker, 'dragend', function () {
            var latlng = mini_map_marker.getLatLng();
            $('PropertyLatitude').value = latlng.lat();
            $('PropertyLongitude').value = latlng.lng();
            $('AddSubmit').disabled = false;
        });
}


	function textChange(request_type) {

	         if (document.contact.request_type.value == "forum_request")
	         {
		         document.getElementById("f_title").innerHTML = "Forum title:";
		         document.getElementById("f_description").innerHTML = "Forum description:";
	         }
	         else
	         {
	             document.getElementById("f_title").innerHTML = "Subject:";
		         document.getElementById("f_description").innerHTML = "Your Comments:";
	         }
	}

	function AccountCheckAllFriends()
	{
	count = document.contacts.elements.length;

	    for (i=0; i < count; i++)
		{
	    if(document.contacts.elements[i].checked == 1)
	    	{document.contacts.elements[i].checked = 0; }
	    else {document.contacts.elements[i].checked = 1;}
		}
	}


	function AccountCheckAllPM()
	{
	count = document.msg.elements.length;

	    for (i=0; i < count; i++)
		{
	    if(document.msg.elements[i].checked == 1)
	    	{document.msg.elements[i].checked = 0; }
	    else {document.msg.elements[i].checked = 1;}
		}
	}


	var newwindow;
	function PopupPicker(url)
	{
		newwindow=window.open(url,'name','width=600,height=650,scrollbars=yes');
		if (window.focus) { newwindow.focus() }
	}


		function SetEmailStr()
        {

            var checkBoxArr = getSelectedCheckboxValue(document.forms["contacts"].MyCheckBox);
            var checkBoxStr = implode(', ', checkBoxArr);

            if (window.opener.document.InviteFriend.email.value != "")
            {
            text = window.opener.document.InviteFriend.email.value = window.opener.document.InviteFriend.email.value + ","  + checkBoxStr;
            }
            else{
            text = window.opener.document.InviteFriend.email.value = window.opener.document.InviteFriend.email.value +  checkBoxStr;
            }

            self.close();
        }

        function implode( glue, pieces ) {
    		return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
		}

		function getSelectedCheckbox(buttonGroup) {

		   var retArr = new Array();
		   var lastElement = 0;
		   if (buttonGroup[0]) {
		      for (var i=0; i<buttonGroup.length; i++) {
		         if (buttonGroup[i].checked) {
		            retArr.length = lastElement;
		            retArr[lastElement] = i;
		            lastElement++;
		         }
		      }
		   } else {
		      if (buttonGroup.checked) {
		         retArr.length = lastElement;
		         retArr[lastElement] = 0;
		      }
		   }
		   return retArr;
		}

		function getSelectedCheckboxValue(buttonGroup) {

		   var retArr = new Array();
		   var selectedItems = getSelectedCheckbox(buttonGroup);
		   if (selectedItems.length != 0) {
		      retArr.length = selectedItems.length;
		      for (var i=0; i<selectedItems.length; i++) {
		         if (buttonGroup[selectedItems[i]]) {
		            retArr[i] = buttonGroup[selectedItems[i]].value;
		         } else {
		            retArr[i] = buttonGroup.value;
		         }
		      }
		   }
		   return retArr;
		}








var ImagePreview = Class.create();
Object.extend(ImagePreview.prototype, {
	element: null,
	name: null,
	update_url: null,
	data: null,
	options: {
			visible: 7,
			data_size: 10,
			interval: 5000,
			image_size: {width: 85, height: 59},
			padding: {top: 2, left: 2, right: 2, bottom: 2},
			mode: 'horizontal'
		},
	image: null,
	interval: null,
	ajax_running: false,

	initialize: function (element, name, update_url, data) {
		this.element = $(element);
		this.name = name;
		this.update_url = update_url;
		this.data = data;
		Object.extend (this.options, arguments[4] || {} );

		if (this.options.mode == 'horizontal') {
			this.options.padding_start = {
					top: Math.round(this.options.image_size.height / 2 + this.options.padding.top),
					left: 0,
					right: 0
				};
			this.options.padding_start.bottom = this.options.image_size.height - this.options.padding_start.top;
		} else {
			this.options.padding_start = {
					top: 0,
					bottom: 0,
					left: Math.round(this.options.image_size.width / 2 + this.options.padding.left)
				};
			this.options.padding_start.right = this.options.image_size.width - this.options.padding_start.left;
		}

		this.image = new Image();

		this.element.update();
		var maxi = this.options.visible > this.data.length ? this.data.length : this.options.visible;
		for (var i = 0; i < maxi; ++i) {

			this.element.insert ({top:
				Builder.node ('a', {href: this.data[i].url, id: this.name + '_' + this.data[i].imgid, title: this.data[i].alt}, [
					Builder.node ('img', {src: this.data[i].img, alt: this.data[i].alt})/*,
					Builder.node ('span', this.data[i].desc)*/ //waiting for location
				])
			});
		}

		this.preload_next();

		this.update ();

		this.interval = setInterval(this.next.bind(this), this.options.interval);
	},

	update: function () {

	    if (this.data.length > this.options.data_size)
			return;

		if (this.ajax_running)
			return;

		this.ajax_running = true;
		var options = '';
		for (i = 0; i < this.data.length; ++i)
			options += '/' + this.data[i].id;

		new Ajax.Request(this.update_url + options, {
                method: 'get',
                onSuccess: this.update_callback.bind(this)
            });
	},

	update_callback: function (transport) {

        eval('var tmp = ' + transport.responseText + ';');

		this.data = this.data.concat(tmp);

		this.preload_next();
		this.ajax_running = false;
	},

	next: function () {

		this.update();

		if (this.data.length <= this.options.visible) {
			return;
		}


		var newElementData = this.data[this.options.visible];
		var newElement = Builder.node('a', {href: newElementData.url, id: this.name + '_' + newElementData.imgid, title: newElementData.alt, style: 'width: 0px; height: 0px; padding-top: ' + this.options.padding_start.top + 'px; padding-left:' + this.options.padding_start.left + 'px; padding-right: ' + this.options.padding_start.right + 'px; padding-bottom: ' + this.options.padding_start.bottom + 'px;'}, [
			Builder.node('img', {src: newElementData.img, alt: newElementData.alt, style: 'width: 0px; height: 0px;'})/*,
			Builder.node('span', newElementData.desc)*/ //waiting for location
		]);
		//$(newElement).childElements()[1].setStyle({opacity: 0}); //waiting for location
		this.element.insert({top: newElement});
		var oldElementName = this.name + '_' + this.data[0].imgid;



		//new Effect.Opacity($$('#' + oldElementName + ' span')[0], {from: 1, to: 0, queue: {scope: this.name, position: 'end'}, duration: 1});  //waiting for location
		new Effect.Parallel([
			new Effect.Morph(oldElementName, {sync: true, style: {paddingTop: this.options.padding_start.top + 'px', paddingLeft: this.options.padding_start.left + 'px', paddingRight: this.options.padding_start.right + 'px', paddingBottom: this.options.padding_start.bottom + 'px', width: '0px', height: '0px'}, afterFinish: function (effect) {effect.element.remove();}}),
			new Effect.Morph(newElement, {sync: true, style: {paddingTop: this.options.padding.top + 'px', paddingLeft: this.options.padding.left + 'px', paddingRight: this.options.padding.right + 'px', paddingBottom: this.options.padding.bottom + 'px', width: this.options.image_size.width + 'px', height: this.options.image_size.height + 'px'}}),
			new Effect.Morph($$('#' + oldElementName + ' img')[0], {sync: true, style: {width: '0px', height: '0px'}}),
			new Effect.Morph(newElement.childElements()[0], {sync: true, style: {width: this.options.image_size.width + 'px', height: this.options.image_size.height + 'px'}})
		], {queue: {scope: this.name, position: 'end'}, duration: 2});
		//new Effect.Opacity($$('#p7 span')[0], {from: 0, to: 1, queue: {scope: this.name, position: 'end'}, duration: 1, afterFinish: function (effect) {$(oldElementName).remove();}});  //waiting for location


		this.data.shift();

		this.preload_next();
	},

	preload_next: function () {
		if (this.data.length > this.options.visible)
			this.image.src = this.data[this.options.visible].img;
	}
});

var propertySearchEnterSearchLocation = function () {
	if ($('PropertySearchForm') && $('PropertyKeyword'))
	{
		var form = $('PropertySearchForm');
		var key = $('PropertyKeyword');

		if ($F(key) == '')
			key.value = trans.enter_location;
		key.observe('focus', function () {
			if ($F(key) == trans.enter_location)
				key.clear();
		});
		key.observe('blur', function () {
			if ($F(key) == '')
				key.value = trans.enter_location;
		});
		form.observe('submit', function () {
			if ($F(key) == trans.enter_location)
				key.clear();
		});
	}
};

Element.observe(window, 'load', propertySearchEnterSearchLocation);

























var LatestContent = Class.create();
Object.extend (LatestContent.prototype, {
    title_element: null,
    text_element: null,
    container: null,
    name: null,
    content_url: null,
    data: [],
    interval: null,
    options: {
        refresh: 6,
        img_dir: '/img/'
    },
    updating: false,
    first_run: true,

    initialize: function (container, name, content_url) {

        this.container = $(container);
        this.name = name;
        this.content_url = content_url;
        Object.extend(this.options, arguments[2] || {});

        this.title_element = $(Builder.node('a', {style: 'font-size: 18px; color: #0675B9; background-color: #E2E8F1;'}));
        this.text_element = $(Builder.node('a', {style: 'color: #000000; background-color: #E2E8F1;'}));


        if (this.name == "landlord_blog_latest_posts")
        {
        	this.link_element = $(Builder.node('a', {style: 'font-size: 14px;'}));
        }
        if (this.name == "landlord_forum_latest_posts")
        {
        	this.link_element = $(Builder.node('a', {style: 'font-size: 14px;'}));
        }

        if (this.name == "landlord_forum_latest_posts" || this.name == "landlord_blog_latest_posts")
        {
            var element = Builder.node ('div', {className: 'rc'}, [
                    Builder.node('h3', {style: 'padding-left: 10px;'}, [this.title_element]),
	                Builder.node('div', {style: 'height: 40px; padding-left: 10px; padding-right: 10px;'}, [
	                   this.text_element,
	                   this.link_element
	                ]
	                ),
	            ]);
        }



        if (this.name == "latest_posts" || this.name == "forum_latest_posts" || this.name == "blog_latest_posts")
        {
	        var element = Builder.node ('div', {className: 'roundcont'}, [
	                Builder.node ('div', {className: 'roundtop'}, [
	                    Builder.node ('img', {className: 'corner', src: this.options.img_dir + 'search_top_left.gif', alt: ''})
	                ]),
	                Builder.node('h3', {style: 'padding-left: 10px;'}, [
	                    this.title_element
	                ]),
	                Builder.node('div', {style: 'height: 40px; padding-left: 10px; padding-right: 10px;'}, [
	                    this.text_element
	                ]),
	                Builder.node ('div', {className: 'roundbottom'}, [
	                    Builder.node ('img', {className: 'corner', src: this.options.img_dir + 'search_bottom_left.gif', alt: ''})
	                ]),
	            ]);
        }

        this.container.setStyle ({opacity: 0});
        this.container.update (element);

        this.update();

        this.interval = setInterval (this.next.bind(this), this.options.refresh * 2000);
    },


    next: function () {
	     this.update();

	     if (this.data.length < 1)
	         return;

	     if (this.first_run) {
	         this.title_element.update (this.data[0].title);
	         this.text_element.update (this.data[0].text);
	         this.title_element.href = this.data[0].url;
	         this.text_element.href = this.data[0].url;

             if (this.name == "landlord_forum_latest_posts" || this.name == "landlord_blog_latest_posts")
        	 {
    	         this.link_element.update (this.data[0].link_title);
        	     this.link_element.href = this.data[0].link_url;
        	 }

	         this.data.shift();
	         new Effect.BlindDown(this.container);
	         new Effect.Opacity(this.container, {
	                 from: 0,
	                 to: 1,
	                 queue: {scope: this.name, position: 'end'}
	             });
	         this.first_run = false;
	         this.update();
	         return;
	     }

        if (this.name == "latest_posts" || this.name == "forum_latest_posts" || this.name == "blog_latest_posts")
        {
		     new Effect.Parallel([
		         new Effect.Opacity(this.title_element, {sync: true, from: 1, to: 0}),
		         new Effect.Opacity(this.text_element, {sync: true, from: 1, to: 0})
		     ], {
		         queue: {scope: this.name, position: 'end'},
		         afterFinish: this.next_continue.bind(this)
		     });
         }
         else
         {
              new Effect.Parallel([
		         new Effect.Opacity(this.title_element, {sync: true, from: 1, to: 0}),
		         new Effect.Opacity(this.text_element, {sync: true, from: 1, to: 0}),
		         new Effect.Opacity(this.link_element, {sync: true, from: 1, to: 0})
		     ], {
		         queue: {scope: this.name, position: 'end'},
		         afterFinish: this.next_continue.bind(this)
		     });

         }

    },

    next_continue: function () {

        this.title_element.update (this.data[0].title);
        this.text_element.update (this.data[0].text);
        this.title_element.href = this.data[0].url;
        this.text_element.href = this.data[0].url;

        if (this.name == "landlord_forum_latest_posts" || this.name == "landlord_blog_latest_posts")
        {
	        this.link_element.update (this.data[0].link_title);
            this.link_element.href = this.data[0].link_url;
        }

        this.data.shift();


		if (this.name == "latest_posts" || this.name == "forum_latest_posts" || this.name == "blog_latest_posts")
        {
        	new Effect.Parallel([
                new Effect.Opacity(this.title_element, {sync: true, from: 0, to: 1}),
                new Effect.Opacity(this.text_element, {sync: true, from: 0, to: 1})
            ], {
                queue: {scope: this.name, position: 'end'}
            });
        }
        else
        {
            new Effect.Parallel([
                new Effect.Opacity(this.title_element, {sync: true, from: 0, to: 1}),
                new Effect.Opacity(this.text_element, {sync: true, from: 0, to: 1}),
                new Effect.Opacity(this.link_element, {sync: true, from: 0, to: 1})
            ], {
                queue: {scope: this.name, position: 'end'}
            });
        }

        this.update();
    },

    update: function () {
        if (this.updating)
            return;
        if (this.data.length > 1)
            return;

        new Ajax.Request(this.content_url, {
                method: 'get',
                onSuccess: this.update_callback.bind(this),
                onException: function () {this.updating = false;}.bind(this),
                onFailure: function () {this.updating = false;}.bind(this)
            });
    },

    update_callback: function (transport) {
        this.updating = false;
        eval ('var tmp = ' + transport.responseText + ';');

        this.data = this.data.concat(tmp);
        if (this.data.length == 0)
        	return;
        if (this.first_run)
            this.next();
    }
});








var PropertyImages = Class.create();
Object.extend(PropertyImages.prototype, {
    element: null,
    default_image: null,
    add_iframe: null,
    uploading: {},
    progress_interval: null,

    initialize: function (element) {
        this.element = element;

        Element.observe(window, 'load', this.init.bind(this));
    },

    init: function () {
        this.element = $(this.element);
        this.property_id = $F('PropertyPropertyId');
        Element.replace(this.element.up(1), this.element);
        $('PropertyImagesForm').remove();

        this.element.childElements().each( this.property_image.bind(this) );

        this.build_new_add_iframe();
    },

    property_image: function (element) {
    	element.addClassName('property_image');
        var image_id = element.id.substring(15);
        var delete_link = $(Builder.node('a', {href: '#', className: 'delete', title: 'delete'}));
        element.down('.top_right').update(delete_link);
        delete_link.observe('click', this.delete_property_image.bind(this, element, image_id));
        var title = Builder.node('h2', $F(element.down('input.text')));
        Element.replace(element.down('input.text'), title);
        element.editor = new Ajax.InPlaceEditor(title, base_web_dir + 'property_images/update_title/' + image_id + '/property_id:' + this.property_id, {
                okText: '',
                submitOnBlur: true
            });
        var def_img = element.down('input.radio').up();
        if (!this.default_image) {
            this.default_image = element;
            def_img.update('This is default image.');
        } else {
            var default_button = $(Builder.node('button', 'Make this image default.'));
            def_img.update(default_button);
            default_button.observe('click', this.set_default_image.bind(this, element));
        }
    },

    delete_property_image: function (element, image_id, event) {

        event.stop();
        Element.replace(element.down('a', 1), Builder.node('img', {src: base_web_dir + 'img/loading.gif'}));
        new Ajax.Request(base_web_dir + 'property_images/delete_image/' + image_id + '/property_id:' + this.property_id, {
                onSuccess: this.delete_property_image_callback.bind(this, element, image_id, true),
                onFailure: this.delete_property_image_callback.bind(this, element, image_id, false),
                onException: this.delete_property_image_callback.bind(this, element, image_id, false)
            });
    },

    delete_property_image_callback: function (element, image_id, success, transport) {
        if (!success || transport.responseJSON.status != 'ok') {
            var delete_link = $(Builder.node('a', {href: '#', className: 'delete', title: 'delete'}));
            element.down('.top_right').update(delete_link);
            delete_link.observe('click', this.delete_property_image.bind(this, element, image_id));
            if (success && transport.responseJSON.status == 'error' && transport.responseJSON.msg && transport.responseJSON.msg.length > 0)
            	alert(transport.responseJSON.msg);
            return;
        }
        new Effect.DropOut (element, {
            afterFinish: function (effect) {
                effect.effects[0].element.remove();
                this.check_default_image();
            }.bind(this),
            duration: 1
        });
    },

    check_default_image: function () {
        var element = this.element.down('li.property_image');
        if (typeof element == 'undefined')
            return;
        if (element == this.default_image)
            return;
        element.down('div', 1).down('div').update('This is default image.');
        this.default_image = element;
        element = element.next('li.property_image');
        while (typeof element != 'undefined') {
            if (typeof element.down('button') == 'undefined') {
                element.down('div', 1).down('div').update($(Builder.node('button', 'Make this image default.')).observe('click', this.set_default_image.bind(this, element)));
            }
            element = element.next('li');
        }
    },

    set_default_image: function (element) {

        this.set_default_button_disabled(true);
        element.down('button').update('Saving...');
        var params = {
        		property_id: this.property_id,
                old_id: this.default_image.id.substring(15),
                old_ext: $F(this.default_image.down('input.ext')),
                new_id: element.id.substring(15),
                new_ext: $F(element.down('input.ext'))
            };
        new Ajax.Request(base_web_dir + 'property_images/swap/' + element.id.substring(15), {
                parameters: params,
                onSuccess: this.set_default_image_callback.bind(this, element, true),
                onFailure: this.set_default_image_callback.bind(this, element, false),
                onException: this.set_default_image_callback.bind(this, element, false)
            });
    },

    set_default_image_callback: function (new_default, success, transport) {
        if (!success || transport.responseJSON.status == 'error') {
            new_default.down('button').update('Make this image default.');
            this.set_default_button_disabled(false);
            if (success && transport.responseJSON.status == 'error' && transport.responseJSON.msg && transport.responseJSON.msg.length > 0)
            	alert(transport.responseJSON.msg);
            return;
        }
        var old_default = this.default_image;

        old_default.down('a.img_link').href = base_web_dir + 'upload/images/properties/' + this.property_id + '/img_' + transport.responseJSON.old_id + '.' + transport.responseJSON.old_ext;
        //old_default.down('img').src = base_web_dir + 'upload/images/properties/' + this.property_id + '/thumb_' + transport.responseJSON.old_id + '.' + transport.responseJSON.old_ext;
        new_default.down('a.img_link').href = base_web_dir + 'upload/images/properties/' + this.property_id + '/img_' + transport.responseJSON.new_id + '.' + transport.responseJSON.new_ext;
        //new_default.down('img').src = base_web_dir + 'upload/images/properties/' + this.property_id + '/thumb_' + transport.responseJSON.new_id + '.' + transport.responseJSON.new_ext;
        old_default.id = 'property_image_' + transport.responseJSON.old_id;
        new_default.id = 'property_image_' + transport.responseJSON.new_id;
        old_default.editor.dispose();
        new_default.editor.dispose();
        old_default.editor = new Ajax.InPlaceEditor(old_default.down('h2'), base_web_dir + 'property_images/update_title/' + transport.responseJSON.old_id + '/property_id:' + this.property_id, {
                okText: '',
                submitOnBlur: true
            });
        new_default.editor = new Ajax.InPlaceEditor(new_default.down('h2'), base_web_dir + 'property_images/update_title/' + transport.responseJSON.new_id + '/property_id:' + this.property_id, {
                okText: '',
                submitOnBlur: true
            });
        var delete_link = $(Builder.node('a', {href: '#', className: 'delete', title: 'delete'}));
        old_default.down('.top_right').update(delete_link);
        delete_link.observe('click', this.delete_property_image.bind(this, old_default, transport.responseJSON.old_id));
        delete_link = $(Builder.node('a', {href: '#', className: 'delete', title: 'delete'}));
        new_default.down('.top_right').update(delete_link);
        delete_link.observe('click', this.delete_property_image.bind(this, new_default, transport.responseJSON.new_id));
        old_default.down('input.ext').value = transport.responseJSON.old_ext;
        new_default.down('input.ext').value = transport.responseJSON.new_ext;

        var old_placeholder = Builder.node('li', ' ');
        var new_placeholder = Builder.node('li', ' ');
        var old_position = old_default.positionedOffset();
        var new_position = new_default.positionedOffset();
        var dady = old_default.getOffsetParent();
        Element.replace(old_default, old_placeholder);
        dady.insert(old_default);
        old_default.setStyle({
                position: 'absolute',
                top: old_position.top + 'px',
                left: old_position.left + 'px',
                width: '100%'
            });
        Element.replace(new_default, new_placeholder);
        dady.insert(new_default);
        new_default.setStyle({
                position: 'absolute',
                top: new_position.top + 'px',
                left: new_position.left + 'px',
                width: '100%'
            });
        new Effect.Parallel([
                new Effect.Move(old_default, {sync: true, x: new_position.left, y: new_position.top, mode: 'absolute'}),
                new Effect.Move(new_default, {sync: true, x: old_position.left, y: old_position.top, mode: 'absolute'})
            ], {
                afterFinish: this.set_default_image_end.bind(this, old_default, new_default, old_placeholder, new_placeholder)
            });
    },

    set_default_image_end: function (old_default, new_default, old_placeholder, new_placeholder) {
        old_default.setStyle({top: '', left: '', position: '', width: ''});
        Element.replace(new_placeholder, old_default);
        new_default.setStyle({top: '', left: '', position: '', width: ''});
        Element.replace(old_placeholder, new_default);
        this.default_image = new_default;
        this.set_default_button_disabled(false);
        Element.replace(new_default.down('button'), 'This is default image.');
        old_default.down('div', 1).down('div').update($(Builder.node('button', 'Make this image default.')).observe('click', this.set_default_image.bind(this, old_default)));
    },

    set_default_button_disabled: function (disabled) {
        this.element.adjacent('button').each(function (e) {
                e.disabled = disabled;
            });
    },

    build_new_add_iframe: function () {
        var iframe = Builder.node('iframe', {frameborder: '0', scrolling: 'no', src: base_web_dir + 'property_images/add/' + this.property_id, className: 'property_image_add'});
        this.element.insert({after: iframe});
        this.add_iframe = $(iframe);
    },

    start_uploading: function (upload_id) {
     	var progress_text = null;
    	var progress_bar = null;
    	var el = $(Builder.node('li', {className: 'uploading_image'}, [
    			Builder.node('a', {className: 'img_link', title: 'uploading...'}),
    			Builder.node('div', {className: 'top_right'}),
    			Builder.node('div', [
    					Builder.node('h2', 'Uploading...'),
    					Builder.node('div', {className: 'progress'}, [
    							progress_text = Builder.node('span', '0%'),
    							progress_bar = Builder.node('div')
    						])
    				])
    		]));
    	this.uploading[upload_id] = {
    			iframe: this.add_iframe,
    			element: el,
    			progress_text: $(progress_text),
    			progress_bar: $(progress_bar)
    		};
    	this.add_iframe.setStyle({
    			visibility: 'hidden',
    			width: 0,
    			margin: 0,
    			padding: 0
    		});
    	this.element.insert({bottom: el});
    	this.build_new_add_iframe();
    	if (this.progress_interval == null)
	    	this.progress_interval = setInterval(this.progress_update.bind(this), 2000);
    },

    finish_uploading: function (property_path, user_id, upload_id, image_id, image_ext, image_title) {

    	this.uploading[upload_id].iframe.remove();
    	var el = this.uploading[upload_id].element;
    	delete this.uploading[upload_id];

     	el.removeClassName('uploading_image');
    	el.addClassName('property_image');
    	el.id = 'property_image_' + image_id;
    	el.down('a.img_link').writeAttribute({
    			title: image_title,
    			rel: 'lightbox',
    			href: base_web_dir + 'upload/images/'+ property_path
    				  + '/img_' + this.property_id + '_' + image_id + '.'
    				  + image_ext})
    		.update(Builder.node('img', {
    			src: base_web_dir + 'upload/images/' + property_path
    				 + '/thumb_' + this.property_id + '_' + image_id + '.'
    				 + image_ext,
    			alt: image_title
    		}));
        var delete_link = $(Builder.node('a', {href: '#', className: 'delete', title: 'delete'}));
        el.down('.top_right').update(delete_link);
        delete_link.observe('click', this.delete_property_image.bind(this, el, image_id));
        var title = Builder.node('h2', image_title);

        el.editor = new Ajax.InPlaceEditor(title, base_web_dir + 'property_images/update_title/' + image_id + '/property_id:' + this.property_id, {
                okText: '',
                submitOnBlur: true
            });


        var default_button = $(Builder.node('button', 'Make this image default.'));
        default_button.observe('click', this.set_default_image.bind(this, el));
        Element.replace(el.down('div', 1), (Builder.node('div', [
        		title,
        		Builder.node('div', [default_button])
        	])));
        el.insert({bottom: Builder.node('input', {
        		className: 'ext',
        		type: 'hidden',
        		value: image_ext
        	})});
        this.element.down('li.uploading_image').insert({before: el});
        this.check_default_image();
        window.myLightbox.updateImageList();
    },

    error_uploading: function (upload_id, error_msg) {
    	this.uploading[upload_id].element.remove();
    	this.uploading[upload_id].iframe.remove();
    	delete this.uploading[upload_id];
    	alert(error_msg);
    },

    progress_update: function () {
    	if (Object.keys(this.uploading).length == 0) {
    		if (this.progress_interval != null) {
	    		clearInterval(this.progress_interval);
	    		this.progress_interval = null;
    		}
    		return;
    	}

    	var p = {};
    	var i = 0;
    	for (j in this.uploading)
    		p['data[upload][' + (i++) + ']'] = j;
    	new Ajax.Request(base_web_dir + 'property_images/upload_status', {
    			parameters: p,
    			onSuccess: this.progress_update_callback.bind(this)
    		});
    },

    progress_update_callback: function (response) {

    	var i = 0;
    	var width = 0;
    	if (response.responseJSON && response.responseJSON.status && response.responseJSON.status == 'ok' && response.responseJSON.upload) {
    		for (i in response.responseJSON.upload)
    			if (this.uploading[i]) {
    				this.uploading[i].progress_text.update(parseInt(response.responseJSON.upload[i]) + '%');
    				width = parseInt(this.uploading[i].progress_bar.up().getWidth() * response.responseJSON.upload[i] / 100.0);
    				this.uploading[i].progress_bar.setStyle({width: width + 'px'});
    			}
    	}
    }
});
