var MAG = function()
{
	this.url = $('script')[0].src.toString().replace(/public.*/g, '');
	this.ajax_url = this.url + 'ajax/';
	this.cache = {
		get_municipalities: {},
		get_towns: {},
		get_urbanizations: {}
	};

	this.ajax_queue = [];
	this.ajax_is_loading = false;
	this.extra_ajax_data = {};
}

MAG.prototype = {
	init_events: function()
	{
		/**
		 * There are some strings which are `KEYs` for the correct functionality.
		 * The strings are: municipality_id and town_id (for now)
		 *
		 * Examples:
		 *  1) <select class="other_class1 other_class2 municipality_id"> - first
		 *     <select id="municipality_id"> - second
		 *	   When the first select is changed, automatically the Ajax request is started and
		 *     the options for the second select are renewed by the AjaxResponse which is in the format JSON
		 *
		 *  2) <select class="other_class1 property_municipality_id"> - first
		 *     <select id="property_municipality_id"> - second
		 *     Functionality is the same as above, because `KEY` string municipality_id
		 *     is contains in the classname
		 *
		 *  3) <select class="other_class1 property_municipality_id"> - first
		 *     <select id="property_municipality_id" class="town_id"> - second
		 *     <select id="town_id"> - third
		 *     The second select is depended on the first, and the third on is depended on the second one
		 *     Notice, if the first changed register the event `change` the options length for second
		 *     will be set to `0` and for the 3th, 4th and so on if exist, will be set to `1`
		 *
		 *  4) <select class="other_class1 property_municipality_id user_municipality_id"> - first
		 *     <select id="property_municipality_id"> - second
		 *     <select id="user_municipality_id"> - third
		 *     In this example, the changed not be register, because the first select contains
		 *     class names, which related to more than one element
		 */
		var selects = [];
		$('select[class]').each(function(i)
		{
			var selects_from_class = $('#'+$(this).attr('class').split(/ +/).join(',#'));
			if(selects_from_class.length == 1)
			{
				var select_id = selects_from_class.attr('id');
				$(this).unbind('change');
				$(this).change(function(e){
					if($MAG.ajax_is_loading) {
						$MAG.ajax_queue.push(this);
						return;
					}
					if(select_id.indexOf('municipality_id') > -1) {
					   var data = {id: $(this).val(), method: 'get_municipalities', province_id: $(this).val(), 'classes': this.className};
                       if(typeof possible_municipalities_ids != 'undefined') {
                            data['possible_municipalities_ids[]'] = possible_municipalities_ids;
                       }
					   $MAG.get_data(data, '#'+select_id);
					}
					else if(select_id.indexOf('town_id') > -1) {
						$MAG.get_data({id: $(this).val(), method: 'get_towns', municipality_id: $(this).val()}, '#'+select_id);
					}
					else if(select_id.indexOf('urbanization_id') > -1) {
						$MAG.get_data({id: $(this).val(), method: 'get_urbanizations',town_id: $(this).val()}, '#'+select_id);
					}
				});
				selects.push(this);
			}
		});
		$(selects).trigger('change');
	},

	get_data: function(data, select)
	{
		if(!this.cache[data.method][data.id])
		{
			var _self = this;
			_self.ajax_is_loading = true;
			$.extend(data, this.extra_ajax_data);
			$.ajax({
				url: this.ajax_url,
				data: data,
				dataType: 'json',
				success: function(response){
					_self.cache[data.method][data.id] = response;
					_self.get_data_complete(response, select);
					_self.ajax_is_loading = false;
					_self.process_queue();
				}
			});
		}
		else {
			this.get_data_complete(this.cache[data.method][data.id], select);
		}
	},

	get_data_complete: function(data, select)
	{
		var sel = $(select);
		var selected_id = sel.val();
		var el = sel, i = 0;
		do {
			el[0].options.length = i++ == 0 ? 0 : 1;
			if(!el.attr('class')) break;
			el = $('#'+el.attr('class').split(/ +/).join(',#'));
		} while(el.length == 1);

		$.each(data, function(i, txt) {
			var option = $('<option />').val(i).text(txt);
			option.appendTo(select);
		});

		if(!$.browser.msie)
		{
			var sel = sel.get(0);
			var opt = $('option', sel).clone();
			sel.options.length = 0;
			$(opt).sort(function(a,b){
				return a.text.toString() == b.text.toString() ? 0 : (a.text.toString() > b.text.toString() ? 1 : -1);
			}).appendTo(sel);
			$(select+" [value="+selected_id+"]").attr('selected', 'selected');
		}
	},

	process_queue: function()
	{
		var el = this.ajax_queue.shift();
		if(el) $(el).trigger('change');
	}
};

function goto_prices() {
    var prices_offset = $('.sales-landing').offset().top - 40;
    $.scrollTo(prices_offset, 300);
}

window.$MAG = new MAG();
$(document).ready(function() {

    if (($('#gotoprice').length > 0) && ($(".sales-landing").length > 0)) {

        $('#gotoprice').contents()
                       .wrapAll('<a href="javascript:goto_prices()" style="outline: none" />');

    }

	// BUBBLE INFO
	$('.infobox').each(function () {
		var trigger = $(this);
		if($('.popup', this).length == 0) {
			trigger.append('<span class="popup">'+ trigger.attr('title') +'</span>');
		}
		if($.browser.msie){
			var info = $('.popup', this).css({display: 'none'});
		} else {
			var info = $('.popup', this).css('opacity', 0);
		}

		var infoboxHeight 		= trigger.height() + parseFloat(trigger.css('padding-top')) + parseFloat(trigger.css('padding-bottom')) + parseFloat(trigger.css('border-top-width')) + parseFloat(trigger.css('border-bottom-width'));
		var infoboxWidth 		= trigger.width() + parseFloat(trigger.css('padding-left')) + parseFloat(trigger.css('padding-right')) + parseFloat(trigger.css('border-left-width')) + parseFloat(trigger.css('border-right-width'));;
		var popupHeight 		= info.height() + parseFloat(info.css('padding-top')) + parseFloat(info.css('padding-bottom')) + parseFloat(info.css('border-top-width')) + parseFloat(info.css('border-bottom-width'));;
		var popupWidth 			= info.width() + parseFloat(info.css('padding-left')) + parseFloat(info.css('padding-right')) + parseFloat(info.css('border-left-width')) + parseFloat(info.css('border-right-width'));;

		var time 			= 250;
		var hideDelay 		= 500;
		var hideDelayTimer 	= null;
		var beingShown 		= false;
		var shown 			= false;

		$([trigger.get(0), info.get(0)]).mouseover(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			if (beingShown || shown) {
				// don't trigger the animation again
				return;
			} else {
				// reset position of info box
				beingShown = true;
				if($.browser.msie){
					info.css({
						display: 'block',
						top: ((0 - popupHeight) + infoboxHeight) - infoboxHeight
					});
					beingShown = false;
					shown = true;
				} else {
					info.css({
						top: (0 - popupHeight) + infoboxHeight,
						display: 'block'
					}).animate({
						top: '-=' + infoboxHeight + 'px',
						opacity: 1
					}, time, 'swing', function() {
						beingShown = false;
						shown = true;
					});
				}
			}
			return false;
		}).mouseout(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				if($.browser.msie){
					info.css({
						display: 'none'
					});
					shown = false;
				} else {
					info.animate({
						top: '+=' + infoboxHeight + 'px',
						opacity: 0
					}, time, 'swing', function () {
						shown = false;
						info.css('display', 'none');
					});
				}
			}, hideDelay);
			return false;
		});
	});

	// Init the the change events for the selects
	$MAG.init_events();

	// Init the tinymce editors
	$('textarea.rich-text').each(function(i, area)
	{
		try {
			tinyMCE.addMCEControl(area, area.name);
		} catch(e) {
			try {
				tinyMCE.execCommand('mceAddControl', false, area.id);
			} catch(e) {}
		}
	});

        if (($("#login").length > 0) && ($('#reg-info').length > 0)) {
            if ($("#login").is(".register-form")) {
                $("#login").find('fieldset').css('height', $('#reg-info').height() + 23);
            }
        }

        if ($("#sales-table").length > 0) {

            function activate_column($table, column_index) {
                $table.find('tr > :nth-child('+column_index+')').addClass('act').filter('.check').addClass('act-check');
            }

            activate_column($("#sales-table"), 4);

            $("td, th", "#sales-table").click( function () {

               var new_index = $(this).prevAll().length + 1;

               if ((new_index > 1) && (new_index < 5)) {
                   $("#sales-table .act").removeClass('act act-check');
                   activate_column($("#sales-table"), $(this).prevAll().length + 1)
               }


            });

        }

});

