/// Frontispiece rotator
/// iwp.su
function parse_str(str, array){	// Parses the string into variables
	// 
	// +   original by: Cagri Ekin
	// +   improved by: Michael White (http://crestidg.com)

	var glue1 = '=';
	var glue2 = '&';

	var array2 = str.split(glue2);
	var array3 = [];
	for(var x=0; x<array2.length; x++){
		var tmp = array2[x].split(glue1);
		array3[unescape(tmp[0])] = unescape(tmp[1]).replace(/[+]/g, ' ');
	}

	if(array){
		array = array3;
	} else{
		return array3;
	}
}

function serialize(obj) {
var str = '';
for (var i in obj) str += i + '=' + obj[i] + '&';
return str.replace(/&$/,'');
}


(function($) {
	$.fn.quotator = function(settings) {
		var config = {'interval': 4000};

		if (settings)
			$.extend(config, settings);
		
		var set = this;
		
		if (set.length > 1) {
			$(set).each(function(i) {
				if (i == 0)
					$(this).addClass('quotator_active').show().css('opacity', 1.0);
				else
					$(this).hide();
			});
			
			setInterval(function() {
				var current = null;
				var next = null;
				$(set).each(function(i) {
					if ($(this).hasClass('quotator_active'))
					{
						current = this;
						next = (set[i+1]) ? set[i+1] : set[0];
					}
				});
				$(current).removeClass('quotator_active').fadeOut(750);
				$(next).addClass('quotator_active').fadeIn(750);
			}, config.interval);
		}
		
		return this;
	};
})(jQuery);

//phones
        function citySelect() {   
            var cities = $(".city-list")
            var arrow = $(".arrow")
            var offset = $(this).offset();
	    var arrowOffset = $("body").hasClass("index") ? 68 : 327
            var arrowPos = Math.round($("#city-selector span:first").width()/2)
            
            var selCity = $(this.firstElementChild).text()
            cities.show()
            arrow.css({"margin-left":arrowPos+arrowOffset+"px"})
            
            var citylink = $(".city-list a:contains("+selCity+")")
            citylink.addClass("selected")
        }
        function setCityPhone() {
            var phone = $(this).siblings().children()
            var prefix = $(phone[0]).text()
            var number = $(phone[1]).text()
            
            $("#phone-select .phone .prefix").text("("+prefix+")")
            $("#phone-select .phone .number").text(number)
            $("#city-selector span:first").text($(this).text())
            var prevSel = $(".city-list a.selected")
            prevSel.removeClass("selected")
            $(".city-list").hide()
            return false
        }
        $(function(){
            
            var cities = $(".city-list .other > div")
            var firstColLength = Math.round(cities.length/2)     
            firstCol = $(cities).slice(firstColLength, cities.length)
            secondCol = $(cities).slice(0, firstColLength)
            $(firstCol).wrapAll("<div class='column span-2' />")
            $(secondCol).wrapAll("<div class='column span-2' />")
            
            $('#frontispiece .tab').quotator();
            
            $('#city-selector').bind('click', citySelect);
            $('.city-list a').bind('click', setCityPhone);
                        $("body").bind('click', function(e) {
                var id = $(e.target).closest("div").attr("id");
                if(id != 'city-selector')
                {
                    $(".city-list").hide()
                }

            })
        });

//leasing list
function leasingSelectChange()
{
	var value = $(this).val();
	var deep = $(this).attr("deep");
	
	var option = $(this.options[this.selectedIndex]);
	
	$("#product-card").addClass("hidden").find("div.cont").html("");
	$("#leasing-select select[deep]").each(function(){
	if($(this).attr("deep")>deep)
		$(this).parents("div.select-parent").remove();
													});
	
	if(value>0)
	{
		if($(option).attr("ch")!=0)
			$.getJSON("/common/ajax/leasing.php",{"id":value,"single":0}, leasingSelectAppend);
		else
			$.getJSON("/common/ajax/leasing.php",{"id":value,"single":1}, leasingShowInfo);
	}
}
function linkAddModel(deep) {
	var findStr = "select[deep="+deep+"]> option:selected";
	
	var model = $(".select-list").find(findStr).text();
	var link = $("#order_link");
	var href = link.attr("href");
	var object = parse_str(href);
	object['model_4'] = model;
	
	link.attr("href", encodeURI(serialize(object)));
}

function leasingShowInfo(data)
{
	var cont = $("#product-card").find("div.cont");
	
	
	
	cont.html("<div class='hr-dotted'></div>");
	cont.append("<h2>"+data.TITLE+"</h2>");
	
	if(data.PREVIEW)
		cont.append("<img src='"+data.PREVIEW+"' />")
	
	cont.append("<div>"+data.BODY+"</div>");
	cont.parent().removeClass("hidden");
	linkAddModel(2);


}

function leasingSelectAppend(data)
{
	$("#product-card").addClass("hidden").find("div.cont").html("");
	if(data.children.length)
	{
		var parent = $("#option_"+data.parent).parent();
		var deep = parseInt(parent.attr("deep"));
		var container = $('<div />').addClass("span-3 pb-10 select-parent clearer");
		
		container.html("<label>&nbsp;</label>").find("label").addClass("column span-1");
				
		if(CHILD_NAMES[deep]!== undefined)
			container.find("label").html(CHILD_NAMES[deep]);
					
		var sel = $("<select />")
					.addClass("column span-2 mb-10")
					.attr({"id":"select_"+data.parent,
						   "autocomplete":"off",
						   "deep":deep+1
						  })
					.html("<option value='0'>&nbsp;</option>");
					
		container.append(sel);
		
		var str = "";
		for(var i in data.children)
		{
			var child = data.children[i];
			str += "<option value='"+child.ID+"' id='option_"+child.ID+"' ch='"+child.CHILDREN_CNT+"'>"+child.TITLE+"</option>";
		}
		sel.append(str)
		
				
		$("#leasing-select .select-list").append(container)
	} else {
		
		linkAddModel(1);
		$("#product-card").removeClass("hidden").find("div.cont").html("");
		
	}
}

$(function(){
	$("#leasing-select").delegate("select","change", leasingSelectChange)		   
})
