$.fn.slowEach = function( interval, callback ) {
    var array = this;
    if( ! array.length ) return;
    var i = 0;
    next();
    function next() {
        if( callback.call( array[i], i, array[i] ) !== false ) 
            if( ++i < array.length )
                setTimeout( next, interval );
    }
};
//doc ready...
$(function(){
	
	$("#main_menu a img").hover(function() {
		var idx = $("#main_menu a img").index(this);
		$(this).attr("src", "images/main_menu"+ (idx+1) +"_active.jpg");									 
	}, function() {
		var idx = $("#main_menu a img").index(this);
	 	$(this).attr("src", "images/main_menu"+ (idx+1) +".jpg");
	});
	
	$("#side_menu ul li a img").hover(function() {
        var idx = $("#side_menu ul li a img").index(this);
        $(this).attr("src", "images/smenuitem_bg_"+ (idx+1) +"_active.jpg");                                     
    }, function() {
        var idx = $("#side_menu ul li a img").index(this);
         $(this).attr("src", "images/smenuitem_bg_"+ (idx+1) +".jpg");
    });
    
    $("#side_menu ul li ul.submenu li").hover(function() {
		$(this).css("background-image", "url(images/submenu_rollover.jpg)").children().css("color", "#175198");    									 
	}, function() {
		$(this).css("background", "none").children().css("color", "#474747");
	});
	
	$("#contact_box a img").hover(function() {
		var idx = $("#contact_box a img").index(this);
		if(idx==0)
			$(this).attr("src", "images/offer_active.jpg");
		else if(idx==1)
			$(this).attr("src", "images/invoicement_active.jpg");
		else if(idx==2)
			$(this).attr("src", "images/error_reporting_active.jpg");
	}, function() {
		var idx = $("#contact_box a img").index(this);
		if(idx==0)
			$(this).attr("src", "images/offer.jpg");
		else if(idx==1)
			$(this).attr("src", "images/invoicement.jpg");
		else if(idx==2)
			$(this).attr("src", "images/error_reporting.jpg");
	});
	
	$("#searchbox input[name=searchtext]").click(function() {
		$(this).val("");			   
	}).blur(function() {
		$(this).val(($(this).val()=="" ? "Írja be a keresendő szöveget..." : $(this).val()));	
	});
    
    subMenu();
    
    /*IE fixes, i like it!*/
    if($.browser.msie) {
        $("ul.submenu").each(function() {
            if($(this).css("left") == "208px") {
                $(this).css("left", "192px");    
            }        
        });
    }
    
    $(".offerform").validate({
        rules: {
            name: "required",
            nationality: "required",
            address: "required",
            local_address: "required",
            phone: "required",
            email: {
                required: true,
                email: true
            }
        },
        errorPlacement: function(error, element) {
            element.css("border", "1px dotted #cd0000");
            $("p.errortext").text('Jelzett mezők kitöltése kötelező!'); 
        },
        success: function() {
            $(".offerform input[type=text]").css("border", "1px solid #C3C3C3");
            $("p.errortext").text("");
        }
    });
    
    $("#searchbox a").click(function() {
        if($("input[name=searchtext]").val() != "" && $("input[name=searchtext]").val() != "Írja be a keresendő szöveget...") {
            var stxt = urlencode($("input[name=searchtext]").val());
            window.location.href = 'index.php?content=search&txt='+stxt;
        }
    });
    
    $("input[name=searchtext]").keypress(function(evt) {
        evt = (evt) ? evt : event;
        var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
        if (charCode == 13 || charCode == 3) {
            $("#searchbox a").trigger("click");    
        }
    });
    
//doc ready end
});

var closeable = false;

function subMenuClose() { 
    to=setTimeout("subMenuClose()", 200);
    if(closeable) {
        $("ul.submenu").hide();
    }
}
subMenuClose();

function subMenu() {

    $("#side_menu > ul > li > a").mouseover(function() {
        $("ul.submenu").hide();
        $(this).next().show();
        closeable = false;
    }).mouseout(function() {
        closeable = true;
    });
    
    $("ul.submenu").mouseover(function() {
        closeable = false;
    }).mouseout(function() {
        closeable = true;
    });
    
    $("ul.submenu > li").mouseover(function() {
        $(this).nextAll("li").children().next().hide();   
        $(this).prevAll("li").children().next().hide(); 
        $(this).children().next().show();
        closeable = false;
    }).mouseout(function() {
        closeable = true;
    });
}  

/* GMAP CODES */
    
var map = null;
var geocoder = null;
                                      
function initialize() {
    if(GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("gmap"));
        map.addControl(new GSmallMapControl());
        //map.setCenter(new GLatLng(46.071206, 18.254471), 13);
        map.setCenter(new GLatLng(46.004116, 18.139114), 10);
        geocoder = new GClientGeocoder();
        
        loadMarks();    
    }
}

function createMarker(point, index) {
    var xicon = new GIcon();
    xicon.image = "images/hotspot.png";
    xicon.iconAnchor = new GPoint(16, 16);
    xicon.iconSize = new GSize(32, 32);

    markerOptions = { icon:xicon };
    var marker = new GMarker(point, markerOptions);

    GEvent.addListener(marker, "click", function() {
        //marker.openInfoWindowHtml("Marker <b>" + letter + "</b>");
    });
    
    return marker;
}

function showAddress(address, idx) {
    if(geocoder) {
        geocoder.getLatLng(
            address,
            function(point) {
                if(!point) {
                    //alert(address + " not found");
                    console.log(address + " not found");
                } else {
                //console.log(address);
                    //map.setCenter(point, 15);
                    map.addOverlay(createMarker(point, idx));
                    //marker.openInfoWindowHtml(address);
                }
            }
        );
    }
}

function loadMarks() {
    $.getJSON("index.php?content=loadgmarks",
        function(data) {
            $(data.address).slowEach(500, function(i, item) {
                showAddress(item, i);
            });            
        }
    );
}

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                                     
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}
