(function($) {
    $.fn.extend({
        customStyle : function(options) {
            if (!$.browser.msie || ($.browser.msie && $.browser.version > 6)) {
                return this.each(function() {

                    var currentSelected = $(this).find(':selected');
                    $(this).after('<span class="customStyleSelectBox"><span class="customStyleSelectBoxInner">' + currentSelected.text() + '</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
                    var selectBoxSpan = $(this).next();
                    var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) - parseInt(selectBoxSpan.css('padding-right'));
                    var selectBoxSpanInner = selectBoxSpan.find(':first-child');
                    selectBoxSpan.css({display:'inline-block'});
                    selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
                    var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
                    $(this).height(selectBoxHeight).change(function() {
                        //selectBoxSpanInner.text($(this).val()).parent().addClass('changed');
                        selectBoxSpanInner.text($(this).find(':selected').text()).parent().addClass('changed');
                        // Thanks to Juarez Filho & PaddyMurphy
                    });
                });
            }
        }
    });
})(jQuery);
jQuery(document).ready(function () {
    $('.menu ul li').hover(
            function () {
                $(this).addClass("hover");
                $(this).find(' > ul').css({ visibility: "visible"});
            },
            function () {
                $(this).removeClass("hover");
                $(this).find(' > ul').css({ visibility: "hidden" });
            }
            );
    $(".spoh").click(function () {
        var par = $(this).parent();
        var hasClass = par.hasClass("spocolactive");
        $(".spoh").parent().removeClass("spocolactive");
        if (!hasClass)
            $(this).parent().addClass("spocolactive");
    });
    var cur = $("a.cur_active").attr("val");
    var refreshPrice = function () {
        $.ajax({
            url: "/printprice.php",
            data: {
                cur: cur,
                period: period,
                cnt:nights
            },
            cache: false,
            context: document.body,
            success: function (data) {
                $("#prices tr").remove();
                $("#prices").html(data);
            }
        });
    };
    $("#cur_list a").click(function () {
        $("a.cur_active").removeClass("cur_active");
        $(this).addClass("cur_active");
        cur = $(this).attr("val");
        refreshPrice();
    });
    $("#periods").val($($("#periods").children("option")[0]).attr("value"));
    $("#periods").change(function () {
        period = $(this).val();
        refreshPrice();
    });
    $("#nights").val($($("#nights").children("option")[0]).attr("value"));
    $("#nights").change(function () {
        nights = $(this).val();
        refreshPrice();
    });
    var period = $("#periods").val();
    var nights = $("#nights").val();
    $('select').customStyle();
    $(".floater").each(function() {
        var fleft = 0;
        var fright = 3;
        var s = $(this);
        var animateTime = 500;
        var div = s.find(".floater_block div");
        var lst = s.find(".floater_block a");
        if(lst.length<=4)return;
        var clear = function(){
                    div.stop();
        };
        var loc = window.location.pathname+window.location.search;
        for(var i = 0; i<lst.length; ++i){
            if($(lst[i]).attr("href")==loc)
            {
//                $(lst[i]).addClass("active");//css("font-weight","bold");
                if(i>lst.length-4)i=lst.length-4;
                div.css("margin-left",(-i*144)+"px");
                break;
            }
        }
        var right_pos = (lst.length-4)*144;
        var speed = 300;
        s.find(".floater_right").mousedown(function(){
            var pos = -parseInt(div.css("margin-left").replace("px",""));
            var dur = Math.abs((right_pos - pos)/speed);
            div.animate({
                marginLeft: (-right_pos)+"px"
            },dur*1000,"linear");
        }).mouseup(clear).mouseout(clear);
        s.find(".floater_left").mousedown(function(){
            var pos = parseInt(div.css("margin-left").replace("px",""));
            var dur = Math.abs(pos/speed);
            div.animate({
                marginLeft: "0px"
            },dur*1000,"linear");
        }).mouseup(clear).mouseout(clear);
    });
    var strt = document.location.href.indexOf("fi=");
    var cnt1 = 0,cnt2 = 0;
    $("a[href]").each(function(){
        if(document.location.pathname.indexOf($(this).attr("href"))>=0)
            $(this).addClass("smactive");
    });

    if (strt >= 0) {
        var fi = parseInt(document.location.href.substr(strt + 3, 3));
        var f1 = function() {
            var t = $(this);
            if (t.attr("href").indexOf("fi=" + fi) >= 0) {
                t.addClass("smactive");
                t.attr("href", "#");
            }
        };
        var cnt = 0;
        var f0 = function() {
            var t = $(this);
            if (t.attr("href").indexOf("fi=" + fi) >= 0) {
                cnt++;
            }
        };
        $(".country_menu a").each(f0);
        cnt1 = cnt;
        if (cnt1 <= 1)
            $(".country_menu a").each(f1);
        cnt = 0;
        $("ul.hlist li ul li a").each(f0);
        cnt2 = cnt;
        if (cnt2 <= 1)
            $("ul.hlist li ul li a").each(f1);
    }
    var collapser = $(".collapser");
    if(collapser.length) {
        var collapse = function() {
            $(".collapsable").hide();
            $(".collapser").show();
            $(this).parent().children(".collapsable").show();
            $(this).hide();
        };
        collapser.click(collapse);
        collapse.call(collapser[(window.location.hash || "").trim("#") ? 1 : 0]);
    }
	var cache = {},lastXhr;
	$( "#weather_box" ).autocomplete({
	    minLength: 2,
		source: function( request, response ) {
		    var term = request.term;
			if ( term in cache ) {
			    response( cache[ term ] );
				return;
			}
            lastXhr = $.getJSON( "backend1.php", request, function( data, status, xhr ) {
			    cache[ term ] = data;
				if ( xhr === lastXhr )
				    response( data );
				});
			},
            autoFocus: true,
            select: function( event, ui){
                $.ajax({
                    url: "/weather.php",
                    data: {
                        n: ui.item.id
                    },
                    cache: false,
                    context: document.body,
                    success: function (data) {
                        $("#weather_block *").remove();
                        $("#weather_block").html(data);
                    }
                });
                //$("#val").val(ui.item.id);
            }
		});
});






function map_initialize(el) {
    var parent = el.parentNode;
    parent.innerHTML = "<div id=\"map\" style=\"width: 420px; height:258px; float:left;\"></div><div id=\"map_find\" style=\"width: 174px; height: 108px; float: left; padding: 80px 10px 0 10px;\"><span>Поиск страны</span><br /><input id=\"country_name\" disabled style=\"border:solid 1px black;\"/></div>"
    function getPaths(str) {
    var parts = str.split(" ");
    var res = [];
    for (var i = 0; i < parts.length; ++i) {
        res[i] = google.maps.geometry.encoding.decodePath(parts[i]);
    }
    return res;
}
/*
function decodeLevels(encodedLevelsString) {
    var decodedLevels = [];
    for (var i = 0; i < encodedLevelsString.length; ++i) {
        var level = encodedLevelsString.charCodeAt(i) - 63;
        decodedLevels.push(level);
    }
    return decodedLevels;
}

function showHotel(e) {
    var v = document.getElementById("hotel_name");
    v.value = this.title;
}

function clickHotel(e) {
}*/

function showPolygon(e) {
    var v = document.getElementById("country_name");
    v.value = this.title;
    this.setOptions({ fillOpacity: 0.3, strokeOpacity:1})
}

function clickPolygon(e) {
    window.location = this.href;
}

function hidePolygon(e) {
    this.setOptions({ fillOpacity: 0, strokeOpacity:0})
}
/*
function showMarker(e) {
    showPolygon.call(this.polygon, e);
}

function clickMarker(e) {
    clickPolygon.call(this.polygon, e);
}

function hideMarker(e) {
    hidePolygon.call(this.polygon, e);
}*/

//            var hot = new google.maps.Marker({n:1973, title:"Maia Luxury Resort and Spa", position: new google.maps.LatLng(-4.716489,55.479047), icon:"/images/bullet_star.png"});
//            hot.setMap(map);
//            google.maps.event.addListener(hot, "mouseover", showHotel);
//            google.maps.event.addListener(hot, "click", clickHotel);

    var map = new google.maps.Map(document.getElementById("map"), {
        zoom: 1
        ,center: new google.maps.LatLng(44.08758487562074, 11.25)
        ,disableDefaultUI:true
        ,mapTypeId: google.maps.MapTypeId.ROADMAP
//        mapTypeId: google.maps.MapTypeId.HYBRID
//        mapTypeId: google.maps.MapTypeId.SATELLITE
//        mapTypeId: google.maps.MapTypeId.TERRAIN
    });
    window.map = map;
    jQuery.ajax({
        url: "/geo.php",
        dataType: "json",
        success: function(config) {
            for (var i = 0; i < config.length; ++i) {
                var c = config[i];
                var polygon = new google.maps.Polygon({
                    n:c.n,
                    title:c.title,
                    paths:getPaths(c.paths),
                    strokeWeight: 1,
                    href: c.href,
                    fillColor:"#ffff00", fillOpacity: 0, strokeOpacity:0, strokeColor:"#ff0000"});
                polygon.setMap(map);
//                if (c.lat || c.lng) {
//                    var cap = new google.maps.Marker({position:new google.maps.LatLng(c.lat, c.lng),icon:"/images/bullet.gif", polygon:polygon });
//                    cap.setMap(map);
//                    google.maps.event.addListener(cap, "mouseover", showMarker);
//                    google.maps.event.addListener(cap, "mouseout", hideMarker);
//                    google.maps.event.addListener(cap, "click", clickMarker);
//                }
                google.maps.event.addListener(polygon, "mouseover", showPolygon);
                google.maps.event.addListener(polygon, "mouseout", hidePolygon);
                google.maps.event.addListener(polygon, "click", clickPolygon);
            }
        }
    });


}
function preventSelection(element){
  var preventSelection = false;

  function addHandler(element, event, handler){
    if (element.attachEvent)
      element.attachEvent('on' + event, handler);
    else
      if (element.addEventListener)
        element.addEventListener(event, handler, false);
  }
  function removeSelection(){
    if (window.getSelection) { window.getSelection().removeAllRanges(); }
    else if (document.selection && document.selection.clear)
      document.selection.clear();
  }
  function killCtrlA(event){
    var event = event || window.event;
    var sender = event.target || event.srcElement;

    if (sender.tagName.match(/INPUT|TEXTAREA/i))
      return;

    var key = event.keyCode || event.which;
    if (event.ctrlKey && key == 'A'.charCodeAt(0))  // 'A'.charCodeAt(0) можно заменить на 65
    {
      removeSelection();

      if (event.preventDefault)
        event.preventDefault();
      else
        event.returnValue = false;
    }
  }

  // не даем выделять текст мышкой
  addHandler(element, 'mousemove', function(){
    if(preventSelection)
      removeSelection();
  });
  addHandler(element, 'mousedown', function(event){
    var event = event || window.event;
    var sender = event.target || event.srcElement;
    preventSelection = !sender.tagName.match(/INPUT|TEXTAREA/i);
  });

  // борем dblclick
  // если вешать функцию не на событие dblclick, можно избежать
  // временное выделение текста в некоторых браузерах
  addHandler(element, 'mouseup', function(){
    if (preventSelection)
      removeSelection();
    preventSelection = false;
  });

  // борем ctrl+A
  // скорей всего это и не надо, к тому же есть подозрение
  // что в случае все же такой необходимости функцию нужно
  // вешать один раз и на document, а не на элемент
  addHandler(element, 'keydown', killCtrlA);
  addHandler(element, 'keyup', killCtrlA);
}
$(".floater").each(function(){preventSelection(this);})
