var rebuildPopupItems = function(elem, dataArr){//rebuilds list of menu sub-items with list given
	var i=0;
	var table = document.createElement('table');
	$(table).attr({
	    'cellspacing' : 0,
	    'cellpadding' : 0
	});
	for(var ind in dataArr){
		if ( (i % 2) == 0 ) {
		    var tr = document.createElement('tr');
		}

		var td = document.createElement('td')
		var li_a = document.createElement('a')
		var li_a_sp = document.createElement('span')
		$(li_a).attr({
		    "href" : 'javascript:void(0);',
		    "id"   : ind
		})
		.click(function(){selectCity(this)});

		$(td)
		    .append(li_a)
			.find('a')
			.append(li_a_sp)
			.find('span')
				.html(dataArr[ind].name);



		$(tr).append(td);
		$(table).append(tr);
		i++;
	}
	$(elem).append(table);
}
var selectorCorrect = function(elem, cfg){//corrects the position and sizes of dropdown
	var diff = cfg.origInner - $('ul li:first a:first span', elem).width() - 10
	$(elem).css({
		left: (cfg.origLeft-(-diff))+'px',
		width: (cfg.origWidth-diff)+'px'
	})
}
var selectCity = function(obj){//changing city in a dropdown
	var id = undefined;
	if (typeof obj == "object") {
	    id = obj.id;
	} else if(typeof obj == "string") {
	    id = obj;
	}

	if(typeof regionNames == 'undefined' || (typeof regionNames[id] == 'undefined' && typeof id != 'undefined'))
		return false
	if(typeof id == 'undefined'){
		for(var ind in regionNames){
			if(regionNames[ind].selected)
				id = ind
		}
	}

	var dt = new Date();
	document.cookie = 'userRegion='+id+'; '+dt.toGMTString()+'; path=/';
	$('#selectedRegionName').html(':&nbsp;'+regionNames[id].name)
	selectorCorrect($('#city-selector'), {
		origWidth: 112,
		origLeft: 720,
		origInner: 105
	});

        if ($('#anketa').length && !$('#anketa').hasClass('anketa-operator')){
            var $select = $('select[name="data[new][city]"]');
            $.get('/webforms/options_cities_by_region', { region_name: regionNames[id].name}, function(data){
                $select.html(data);
                $select.trigger('change');
            });
        }

	setTimeout($.unblockUI, 10);
}

var selectFeedBack = function(id){
    var message = '&nbsp;', descr='&nbsp;';
	switch(id) {
	    case 0:
	        message='&mdash;&nbsp;Оставь свои пожелания по телефону: <strong>8-800-700-65-65</strong>';
	        descr='Звонок бесплатный';
		    break;		    
	    case 1:
	        message='&mdash;&nbsp;Отправь SMS «ОК» на номер: <strong>1500</strong>';
	        descr='Цена SMS не более 1,77&nbsp;руб (контент в&nbsp;подарок)';
	        break;
            case 2:
	        message='&mdash;&nbsp;Пройди опрос на терминале оплаты';
			descr='после внесения платежа';
		    break;	        
	}
	
	$('.losung h1').animate({opacity: 0},'fast',function(){
	    $(this).html(message).animate({opacity: 1},'fast');
	});
	$('.losung b').animate({opacity: 0},'fast',function(){
	    $(this).html(descr).animate({opacity: 1},'fast');
	});
}

var initSelectCity = function(){
    
    $("#city-selector").click(function() {
        $.blockUI({
	    //centerX: true,
	    //centerY: true,
            theme:     false,              // true to enable jQuery UI CSS support
            draggable: true,                  // draggable option requires jquery UI
            //title:    'My Title',             // only used when theme == true
            message:  $("#select_rigions")   // message to display
            //timeout:   3000                   // close block after 3 seconds (good for demos, etc)
	    ,css: {
		top:  ($(window).height() - 600) /2 + 'px',
                left: ($(window).width() - 550) /2 + 'px',
		border: 'none',
		cursor: 'default',
		backgroundColor: 'transparent'
	    },
	    overlayCSS: {
		cursor: 'default',
		opacity: 0.4
	    }

        });

	$('.popup-close').attr('title','Click to unblock').click($.unblockUI);
	$('.blockOverlay').attr('title','Click to unblock').click($.unblockUI);
    });
}

var FaqSlide = function(){
    $('#faq a.expander').click(function(){
            $(this).parent().next('div.hidden').slideToggle(function(){
                $(this).toggleClass('expanded')
            });
            return false;
        });
}

$(document).ready(function(){
    initSelectCity();
    $('.popup-selector')
		.live('mouseout', function(){$(this).find('li:not(.select-sb)').hide()})
		.live('mouseover', function(){$(this).find('li:not(.select-sb)').show()})
	
//	rebuildPopupItems($('#city-selector'), regionNames)
	rebuildPopupItems($('.popup_box_content'), regionNames)

	
	var sp = document.cookie.split(';')
	var defaultCity = undefined
	for(var i in sp){
		var code = sp[i].split('=')
		if($.trim(code[0]) == 'userRegion'){
			defaultCity = $.trim(code[1]);
		}
	}
	selectCity(defaultCity)
        FaqSlide();
        
});


