$(function () {


function select_innerHTML(objeto,innerHTML)
{
    objeto.innerHTML = ""
    var selTemp = document.createElement("micoxselect")
    var opt;
    selTemp.id="micoxselect1"
    document.body.appendChild(selTemp)
    selTemp = document.getElementById("micoxselect1")
    selTemp.style.display="none"
    if(innerHTML.indexOf("<option")<0){//se na~o e' option eu converto
        innerHTML = "<option>" + innerHTML + "</option>"
    }
    innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span")
    selTemp.innerHTML = innerHTML
    
    for(var i=0;i<selTemp.childNodes.length;i++){
        var spantemp = selTemp.childNodes[i];
        if(spantemp.tagName){
            opt = document.createElement("OPTION")
            if(document.all){ //IE
                objeto.add(opt)
            }else{
                objeto.appendChild(opt)
            }
            
            //getting attributes
            for(var j=0; j<spantemp.attributes.length ; j++){
                var attrName = spantemp.attributes[j].nodeName;
                var attrVal = spantemp.attributes[j].nodeValue;
                if(attrVal){
                    try{
                        opt.setAttribute(attrName,attrVal);
                        opt.setAttributeNode(spantemp.attributes[j].cloneNode(true));
                    }catch(e){}
                }
            }
            
            //getting styles
            if(spantemp.style){
                for(var y in spantemp.style){
                    try{opt.style[y] = spantemp.style[y];}catch(e){}
                }
            }
            
            //value and text
            opt.value = spantemp.getAttribute("value")
            opt.text = spantemp.innerHTML
            
            //IE
            opt.selected = spantemp.getAttribute('selected');
            opt.className = spantemp.className;
        }
    }
    
    document.body.removeChild(selTemp)
    selTemp = null
}


var options_country='';
var options_ukr='';
var is_selected='';
var is_selected_country='';
var flag_selected_country=0;
var style_count='';
var flag_selected=0;
var flag_selected_0=0;
var RegSel = document.getElementById('auth.region_id');



var i;
if (document.getElementById('auth.region_id')) {
	for (i = 0 ; i<=RegSel.length - 1; i++) {
		if (RegSel.options[i].value > 100) {
			options_country += '<option value="' + RegSel.options[i].value + '"' + is_selected_country + '>' + RegSel.options[i].text + '</option>';
			RegSel.remove(i);
			i--;
		} else {
			if(RegSel.options[i].value == 100){
				style_count=' style="background-color:#F5691D;"';
			} else {
				style_count='';
			}
			options_ukr += '<option value="' + RegSel.options[i].value + '"' + is_selected + style_count +'>' + RegSel.options[i].text + '</option>';
		}
	}
}


//options_ukr += '<option value="100" style="background-color:#F5691D;">Другая страна</option>'; 
options_country += '<option value="101">Украина</option>';

//select_innerHTML(document.getElementById("auth.region_id"),options_ukr);

//alert(options_country);
//alert(options_ukr);

if(flag_selected_country == 1){
	//$("#auth.region_id").html(options_country);
	select_innerHTML(document.getElementById("auth.region_id"),options_country);
}

$('#auth.region_id').change(function(){
	if(document.getElementById('auth.region_id') && document.getElementById('auth.region_id').value < 100){
		RegSel = document.getElementById('auth.region_id');
		options_ukr='';
		var i;
		for (i = 0 ; i<=RegSel.length - 1; i++) {
			if (RegSel.options[i].selected) {
				is_selected=' selected="true"';
				flag_selected=RegSel.options[i].value;
			}else{
				is_selected='';
			}
			if(RegSel.options[i].value == 100){
				style_count=' style="background-color:#F5691D;"';
			} else {
				style_count='';
			}
			options_ukr += '<option value="' + RegSel.options[i].value + '"' + is_selected + style_count +'>' + RegSel.options[i].text + '</option>';
		}
	}
});


    var is_logon = $.cookie('logon') == "yes" ? true : false;
    var sLang = $("html").attr("lang");
    // var jLoginFormContainer = $("#login-form");
    var jSalesFormContainer = $("#increase-sales");
    // var jLoginInput = $("#auth_name");
    // var jPasswdInput = $("#auth_passwd");
    // var jSubmit = $(":submit",jLoginFormContainer);
    // var sUserName = $.cookie('auth.name');
    // var jElementToFucus = jLoginInput;
    // var jErrors = jLoginFormContainer.find(".errors");
    // jErrors.addClass("hidden");
    // var jLoginForm = jLoginFormContainer.find("form");
    var oFormData = {};
    var isAuthErrors = false;
    //if(jLoginInput.get(0) && sUserName){
    //    jLoginInput.get(0).value = sUserName;
    //    jLoginInput.change();
    //    jElementToFucus = jPasswdInput;
    //}

    if (document.getElementById("form_authorisation")){
        ZForms.getFormById("form_authorisation").enableSubmit();
    }


    /* ajax-submit формы авторизации (1.0) */
    /*
	jLoginForm.submit(function(){

		var result = true;
		jErrors.addClass("hidden");
		// собираем данные формы
		oFormData = {"is_ajax": "true", lang: sLang, region: sRegionAbbr};
		jLoginForm.find("input").each(function () {
			oFormData[this.name] = this.value;
		});
		$.getJSON(
			'/_ajax/auth/',
			oFormData,
			function(data){
				if (data.js.status === "error") {
					jErrors.html(data.js.message).removeClass("hidden");
				} else {
					if(data.js.redirect_url){
						document.location = data.js.redirect_url;
					}else{
						document.location.reload();
					}
				}
			},
			"json"
		);
		return false;
	});
    */
    
    
    /* Lightbox регистрации (1.0) */
	/*
	var oPopupRegistration = popup_block({
		container: $("#registration-form"),
		link: $("#registaration-link"),
		fader: $("#fader"),
		close: $("#registration-form span.btn-close"),
		onBlockShow: function(){
			oPopupLogin.hide();
			jElementToFucus.focus();
			jErrors.addClass("hidden");
			//window.setTimeout(function(){
			//	var zF = ZForms.getFormById("form_authorisation");
			//	//var zW = zF.getWidgetById("auth_passwd");
			//	if(jPasswdInput.get(0).value){ zF.enableSubmit() }
			//}, 1000);
		}
	});
	*/

	/* Lightbox регистрации (2.0) */
    /*
	var oPopupRegistration = popup_block({
		container: $("#registration-form"),
		link: $("#registaration-link"),
		fader: $("#fader"),
		close: $("#registration-form span.btn-close"),
		onBlockShow: function()
		{
			oPopupLogin.hide();

			$('#reg_type_chooser').show();
			$('#form_registration').hide();

			jElementToFucus.focus();
			jErrors.addClass("hidden");

			if (this.onResize) {
				this.onResize.call(this);
			}
		},
		onBlockHide: function()
		{
		},
		onResize: function()
		{
			if (oPopupRegistration.container.length) {
				if (!oPopupRegistration.container.hasClass('hidden')) {
					var fr_width = oPopupRegistration.container.width();
					oPopupRegistration.container.css('left', ($(window).width() - oPopupRegistration.container.width()) / 2);
				}
			}
		}
	});

	$(window).bind('resize', oPopupRegistration.onResize);
    */

	var oPopupHot1  = popup_block({
		container: $("#hot-form1"),
		link: $("#hot-link-main"),
		fader: $("#fader"),
		close: $("#hot-form1 span.btn-close"), 
		onBlockShow: function(){
			oPopupHot2.hide();
//			jErrors.addClass("hidden");
		}
	});
	
	var oPopupHot2  = popup_block({
		container: $("#hot-form2"),
		link: $("#hot-link-main2"),
		fader: $("#fader"),
		close: $("#hot-form2 span.btn-close"), 
		onBlockShow: function(){
			oPopupHot1.hide();
//			jErrors.addClass("hidden");
		}
	});
	
	

	var oPopupSales  = popup_block({
		container: $("#increase-sales"),
		link: $("#sale-link-main"),
		fader: $("#fader"),
		close: $("#increase-sales span.btn-close"),
		onBlockShow: function(){
			oPopupInteriorphoto.hide();
			oPopupPriemi.hide();
			oPopupArciphoto.hide();
			$("#priemi-link").focus();
//			jErrors.addClass("hidden");
		}
	});
	
	var oPopupSales_back  = popup_block({
		container: $("#increase-sales"),
		link: $("#sale-link"),
		fader: $("#fader"),
		close: $("#increase-sales span.btn-close"),
		onBlockShow: function(){
			oPopupPriemi.hide();
			oPopupInteriorphoto.hide();
			oPopupArciphoto.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});
	
	var oPopupSales_back1  = popup_block({
		container: $("#increase-sales"),
		link: $("#sale1-link"),
		fader: $("#fader"),
		close: $("#increase_sales span.btn-close"),
		onBlockShow: function(){
			oPopupPriemi.hide();
			oPopupInteriorphoto.hide();
			oPopupArciphoto.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});
	
	var oPopupSales_back2  = popup_block({
		container: $("#increase-sales"),
		link: $("#sale2-link"),
		fader: $("#fader"),
		close: $("#increase-sales span.btn-close"),
		onBlockShow: function(){
			oPopupPriemi.hide();
			oPopupInteriorphoto.hide();
			oPopupArciphoto.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});
	
		var oPopupSales_back  = popup_block({
		container: $("#increase-sales"),
		link: $("#sale-linkh"),
		fader: $("#fader"),
		close: $("#increase-sales span.btn-close"),
		onBlockShow: function(){
			oPopupPriemi.hide();
			oPopupInteriorphoto.hide();
			oPopupArciphoto.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});
	
	var oPopupSales_back1h  = popup_block({
		container: $("#increase-sales"),
		link: $("#sale1-linkh"),
		fader: $("#fader"),
		close: $("#increase_sales span.btn-close"),
		onBlockShow: function(){
			oPopupPriemi.hide();
			oPopupInteriorphoto.hide();
			oPopupArciphoto.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});
	
	var oPopupSales_back2h  = popup_block({
		container: $("#increase-sales"),
		link: $("#sale2-linkh"),
		fader: $("#fader"),
		close: $("#increase-sales span.btn-close"),
		onBlockShow: function(){
			oPopupPriemi.hide();
			oPopupInteriorphoto.hide();
			oPopupArciphoto.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});
	
	var oPopupArciphoto = popup_block({
		container: $("#archiphoto-form"),
		link: $("#archiphoto-link"),
		fader: $("#fader"),
		close: $("#archiphoto-form span.btn-close"),
		onBlockShow: function(){
			oPopupSales.hide();
			oPopupInteriorphoto.hide();
			oPopupPriemi.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});

	var oPopupArciphotoDetail = popup_block({
		container: $("#archiphoto-form"),
		link: $("#archiphoto-link-detail"),
		fader: $("#fader"),
		close: $("#archiphoto-form span.btn-close1"),
		onBlockShow: function(){
			oPopupSales.hide();
			oPopupInteriorphoto.hide();
			oPopupPriemi.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});
	
	var oPopupInteriorphoto = popup_block({
		container: $("#interiorphoto-form"),
		link: $("#interiorphoto-link"),
		fader: $("#fader"),
		close: $("#interiorphoto-form span.btn-close"),
		onBlockShow: function(){
			oPopupSales.hide();
			oPopupArciphoto.hide();
			oPopupPriemi.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});
	
	var oPopupInteriorphotoDetail = popup_block({
		container: $("#interiorphoto-form"),
		link: $("#interiorphoto-link-detail"),
		fader: $("#fader"),
		close: $("#interiorphoto-form span.btn-close1"),
		onBlockShow: function(){
			oPopupSales.hide();
			oPopupArciphoto.hide();
			oPopupPriemi.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});
	
	var oPopupPriemi = popup_block({
		container: $("#priemi-form"),
		link: $("#priemi-link"),
		fader: $("#fader"),
		close: $("#priemi-form span.btn-close"),
		onBlockShow: function(){
			oPopupSales.hide();
			oPopupArciphoto.hide();
			oPopupInteriorphoto.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});

	var oPopupPriemiDetail = popup_block({
		container: $("#priemi-form"),
		link: $("#priemi-link-detail"),
		fader: $("#fader"),
		close: $("#priemi-form span.btn-close1"),
		onBlockShow: function(){
			oPopupSales.hide();
			oPopupArciphoto.hide();
			oPopupInteriorphoto.hide();
//			jElementToFucus.focus();
//			jErrors.addClass("hidden");
		}
	});
    
    
    
    if (is_logon){
        // нужно загрузить пользовательские данные (визитку и ссылки на заявки)
        $.post(
            "/_ajax/auth/data.html",{
                lang: sLang,
                region: sRegionAbbr
            },
            function(data)
            {
                if ($.trim(data) == '')
                {
                    $("#main_requests_links").hide();
                    $("#site_sections div.profile").removeClass("hidden");
                }
                else
                {
                    data =  eval('('+data+')');
                    $("#site_sections div.profile")
                        .addClass("profile-enabled")
                        .html(data.js.personal_block)
                        .removeClass("hidden");
                    // $("#main_requests_links").html(data.js.app_links);
                    $("#main_requests_links").hide();
                }
            }
        );
    } else {
        $("#main_requests_links").hide();
        $("#site_sections div.profile").removeClass("hidden");
    }


	/* Блок "Гляди, что здесь Est!" */
	LookHere = function(jContainer){
		if(!jContainer.length) return;
		var that = this;
		that.container = jContainer;
		that.data = $("div.datanew",jContainer);
		that.content = $("div.content",jContainer);
		that.reloader = $(".reloader:first",jContainer);
		var iBlockAmount = that.data.length;
		var iCurrentBlock = Math.round(Math.random()*(iBlockAmount-1));
                iCurrentBlock = 0; // don't randomize first feature

		that.refreshContent = function(){
			that.content.html(that.data.eq(iCurrentBlock).html());
		};

		that.reloader.click(function(){
			if((iCurrentBlock+1) == iBlockAmount){
				iCurrentBlock = 0;
			} else {
				iCurrentBlock += 1;
			}
			that.refreshContent();
			return false;
		});

                that.refreshContent();
	};

    // 28.11.2010 zema
    // load features from symfony part of site (/features.json)
    if ($("#info_box").length)
    {
        $.ajax({
            'url': '/services.json',
            'dataType': 'json',
            'data': {
                'path': location.pathname,
                'host': location.hostname
            },
            success: function(data)
            {
                var box = $('#info_box');
                var feature, features = [];
                for (var i = 0; i < data.count; i++)
                {
                    feature = data.items[i];
                    if (feature.link)
                    {
                        features.push('<div class="datanew" style="display: none"><a type="leaf" href="' + feature.link + '"><img class="art" src="' + feature.icon + '" alt="" /></a><p>' + feature.look + '</p></div>');
                    }
                    else
                    {
                        features.push('<div class="datanew" style="display: none"><a type="leaf"><img class="art" src="' + feature.icon + '" alt="" /></a><p>' + feature.look + '</p></div>');
                    }
                }
                $('div.content', box).after(features.join('\n'));
                $('div.data', box).remove();
                LookHere(box);
                box.show();
            }
        });
    }

	// LookHere( $("#info_box") );
});

