var waitingforajaxcall = "<div class='tempLoading'><img src='core/media/img/ajax-loader.gif' alt='ajax-loader' /><span>Attendere..</span></div>";

var ipermercatinumber = 0; 
var supermercatinumber = 0;
var expressnumber = 0;

var logged = false;

/*
 * These functions should be here because else they are not found
 */

function getStringAddress(address, civic, city, cap, province){
    var ddd = address + ", ";
    if (civic != null && civic != "") {
        ddd += civic + ", ";
    }
    ddd += cap + " " + city + " " + province;
    
    return ddd;
}

function findPath(address, civic, cap, city, province, latitude, longitude){
	$("#controltab2").show();
    ddd = getStringAddress(address, civic, city, cap, province);
    $("#directions_to").val(ddd);
    $("#latitudeToField").val(latitude);
    $("#longitudeToField").val(longitude);
	
	$("#controltab2").attr("href", "#storelocator-tab2");
    jQuery("#controltab2").click();
    resetSearch();
}

function resetSearch() {
	$("#directions").hide();
    $("#searchDirections").show();
}

function getTitle(marker){
    return marker.getAttribute("name");
}

function addToMyCarrefour(event){
    //building animated div
    //jQuery(this).after("<div id='calling' style=''></div>");
    jQuery(this).hide().after(waitingforajaxcall);
    var code = jQuery(this).attr('id').substring(9, jQuery(this).attr('id').length);
    
    $.getJSON("/AjaxRpc/storeLocator.addFavoritePdv?codicePdv=" + code, null, function(data, textstatus){
        if (data.result) {
            eval("bean=" + data.data);
            $(".tempLoading").remove();
            alert("Il punto vendita preferito è stato correttamente aggiornato!");
            window.location = bean['address'];
        } else {
            alert(data.message);
            $(".tempLoading").remove();
            //jQuery(this).show();
            if (data.data != null) {
            	eval('bean=' + data.data);
            	if (bean['register'] != null) {
            		window.location = "/index-registration.html?&puntoVendita=" + escape(bean['codicePuntoVendita']);
            	}
            }
        }
    });
}

function removeFromMyCarrefour(event){
    //building animated div
    //jQuery(this).after("<div id='calling' style=''></div>");
    jQuery(this).hide().after(waitingforajaxcall);
    var code = jQuery(this).attr('id').substring(14, jQuery(this).attr('id').length);
    
    $.getJSON("/AjaxRpc/storeLocator.removeFavoritePdv?codicePdv=" + code, null, function(data, textstatus){
        if (data.result) {
            //eval("bean=" + data.data);
            $(".tempLoading").remove();
            // changing link
            var html = "<a class='aggiungi add' href='#' id='addToMyC4" + code + "'>Aggiungi in MyCarrefour</a>";
            jQuery(this).after(html).remove();
        }
        else {
            alert(data.message);
            $(".tempLoading").remove();
            jQuery(this).show();
        }
    });
}

$(document).ready(function(){
	//checking if logged
	var cookie = $.cookie("jcmUserCookie");
	if (cookie != null && cookie != '' && cookie != 'undefined') {
		logged = true;
	}
	
	$("#search_map").focus();
    
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(41.87194, 12.56738), 5);//centering of italy
        map.setUIToDefault();
        
        var geocoder = new GClientGeocoder();
        geocoder.setBaseCountryCode('it');
        
        var directionsPanel = document.getElementById("directions");
        var directions = new GDirections(map, directionsPanel);
        
        GEvent.addListener(directions, "load", function(){
            $(".tempLoading").remove();
        });
        GEvent.addListener(directions, "error", function(){
            alert("Inserire l'indirizzo secondo il formato indicato");
            $(".tempLoading").remove();
            resetSearch();
        });
        
//        var gsize = new GSize(350, 200);
//        var infowindow = map.getInfoWindow();
//        infowindow.reset(this.getPoint(),infoWindow.getTabs(),new GSize(350,200),null,null);
        
        $("#search_map").submit(function(){
            // resetting global variables
            supermercatinumber = 0;
            ipermercatinumber = 0;
            expressnumber = 0;
            
//        	alert("search");
            map.clearOverlays();
            // centering on given location
            centerAddress($("#location_searchField").val());
            $("#search_map").focus();
            return false;
        });
        var travelmode = "G_TRAVEL_MODE_DRIVING";
        
        $("#submitDirections").click(function(){
            jQuery("#directions").append(waitingforajaxcall);
            jQuery.each($("#locomotionList").selectedValues(), function(index, value){
                travelmode = value;
            });
            var to = $("#directions_from").val(); 
            if (to.toLowerCase().indexOf("italia") == -1) {
            	to += " italia";
            	$("#directions_from").val(to);
            }
            var path = "from: " + $("#directions_from").val() + " to: " + $("#latitudeToField").val() + "," + $("#longitudeToField").val();
            //alert(path);
            //alert(travelmode);
            
            directions.load(path, {
                travelMode: travelmode,
                locale: 'it'
            });
        });
    }
    
    $("#cancelDirections").click(function(){
        $("#directions_from").val("");
        $("#directions_to").val("");
    });
    
	$("#controltab2").hide();
//	$("#controltab2").attr('href','#');
	
    $("a[id*='addToMyC4']").live('click', addToMyCarrefour);
    $("a[id*='removeFromMyC4']").live('click', removeFromMyCarrefour);
    
    var cmd = $.getUrlVar('cmd');

    // pre-selecting filter if parameter is found on the url
    var openfilter = false;
    $(":checkbox[name='services']").each(function(){
    	var value = $.getUrlVar(escape(jQuery(this).val()));
	
    	if (value != null) {
    		jQuery(this).attr("checked", "checked");
    		openfilter = true;
    	}
    });
    if (openfilter) {
    	//alert("click");
    	$("#toggle-store_criteria").click();
    }    

    // maybe there is a location set
    var location = $.getUrlVar('location');
    if (location != null) {
    	$("#location_searchField").val(location);
    }

    //checking if we come from myc4 page - we could calculate path or find pdv
    var puntovenditacode = $.getUrlVar('codicePdv');

    if (puntovenditacode != null && cmd != null) {
//    	alert("dehiho");
    	// should init direction panel or map!
    	// ajax call to retrieve pdv data
    	$.getJSON(	"/AjaxRpc/storeLocator.getPuntoVenditaAddress?codicePdv=" + puntovenditacode, 
    				null, 
    				function(data, textstatus){
    					if (data.result) {
				            //alert(data.data);
				            var puntovendita = eval('(' + data.data + ')');
				            if (cmd == 'calculate') {
					            findPath(	puntovendita.via, 
					            			puntovendita.numeroCivico, 
					            			puntovendita.cap, 
					            			puntovendita.comune, 
					            			puntovendita.provincia, 
					            			puntovendita.latitudine, 
					            			puntovendita.longitudine);
    						} else if (cmd == 'view') {
//    							/*if(cmd == 'extraOpen') {
//    								var today = new Date();
//    								var date = today.getDay() + "/" + (today.getMonth() + 1) + "/" + today.getYear();
//    								var newdate = {date : "Oggi"};
//    								$("#apertureList").addOption(newdate,true);
//    							}*/
				            	$("#location_searchField").val(getStringAddress(puntovendita.via, 
														            			puntovendita.numeroCivico, 
														            			puntovendita.cap, 
														            			puntovendita.comune, 
														            			puntovendita.provincia));
				            	$("#search_map").submit();
				            }
    					} else {
    						alert(data.message);
    					}
        });    	
    } 
    
    var codiceAziendale = $.getUrlVar('codiceAziendale');
    var stageExec = $.getUrlVar('stageExec');    
    if(codiceAziendale != null && stageExec != null) {
    	$("#codiceAziendale").val(codiceAziendale);
    	$("#stageExec").val(stageExec);
    }
    
    // getting next extra openings
    $.getJSON("/AjaxRpc/storeLocator.getExtraOpen", null, function(data, textstatus){
        //alert(data.data);
        var aperture = eval('(' + data.data + ')');
        $("#apertureList").addOption(aperture, false);
        
        // maybe there is extraopen to set
        var extraopen = $.getUrlVar('extraOpen');
        if(extraopen != null) {
        	if ($("#apertureList").containsOption(extraopen)) {
//        		alert("contains! selecting " + extraopen);
        		$("#apertureList").selectOptions(extraopen);
        	} else {
//        		alert("adding " + extraopen);
        		$("#apertureList").addOption(extraopen, extraopen, true);
        	}
    	}
        
        // search should be triggered only after returning from getting extra opens
        if(cmd == 'search') {
        	$("#search_map").submit();
        }
    });
        
    /*
     * Utility functions
     */    
    function centerAddress(address){
        geocoder.getLatLng(address + " italy", function(point){
            if (!point) {
                alert(address + " non trovato!");
            } else {
                geocoder.getLocations(point, function(response){
                	if (!response || response.Status.code != 200) {
                        alert("\"" + address + "\" not found qui");
                    } else {
                        var index = -1;
                        for (var i = 0; i < response.Placemark.length; i++) {
                        
                            if (response.Placemark[i].AddressDetails.Country.CountryNameCode == 'IT') {
                                index = i;
                            }
                        }
                        var html = "<div class='resultat balloon1' id='noResults'>" +
				        				"<div class='result_text'>" +
				                    		"<p>Siamo spiacenti, nessun punto vendita corrisponde ai criteri selezionati, ti invitiamo a cambiare i criteri di ricerca.</p>" +
				                		"</div>" +
				            		"</div>";
                        if (index != -1) {                            
                            //*******
                            var bounds, swBounds, neBounds;
                            map.setCenter(point, 10);
                            /*var marker = new GMarker(point);
                             map.addOverlay(marker);
                             marker.openInfoWindowHtml(address);*/
                            bounds = map.getBounds();
                            swBounds = bounds.getSouthWest();
                            neBounds = bounds.getNorthEast();
                            $("#centerLat").val(point.y);
                            $("#centerLon").val(point.x);
                            $("#north").val(neBounds.lat());
                            $("#south").val(swBounds.lat());
                            $("#east").val(neBounds.lng());
                            $("#west").val(swBounds.lng());
                            // looking for stores
                            //    												$("#storelocator-tab1").block({
                            //    						    				        message: "Attendere..."
                            //    						        });
                            
                            $("#storelocator-tab1").empty().append(waitingforajaxcall);
                            $.post(	"/solutions/carrefour/storeLocator/searchStores.jsp", 
                            		$("#search_map").serialize(), 
                            		function(data){		                                
		                                $(".tempLoading").remove();
		                                $("#storelocator-tab1").empty();
		                                xml = data;
		                                var markers = xml.documentElement.getElementsByTagName("marker");
		                                if (markers.length > 0) {                               
		                                    for (var i = 0; i < markers.length; i++) { 
		                                    	//alert("lat " + parseFloat(markers[i].getAttribute("lat")));
		                                        //alert("lng " + parseFloat(markers[i].getAttribute("lng")));
		                                        html = generateHtmlForMarker(markers[i]);
		                                        // appending html to result tab
		                                        $("#storelocator-tab1").append(html);
		                                        //adding marker to map
		                                        var mapmarker = createMapMarkerHtml(markers[i], html);
	                                        	map.addOverlay(mapmarker);
	                                        	if (i == 0 && cmd == 'view' && puntovenditacode != null) {
	                                        		// making baloon appearing if came from store details page
	                                        		GEvent.trigger(mapmarker, "click");
	                                        	}
		                                    }
		                                } else {
		                                	// take attention - if there are no markers, html variable value is something like "No results"
		                                	$("#storelocator-tab1").append(html);
		                                }
		                                // $("#storelocator-tab1").unblock();
		                                //alert("Data Loaded: " + data);    						          			
		                                // cleaning interface
		                                resetSearch();
		                                $("#cancelDirections").click();
                            		}, 
                            		"xml");  
                        } else {
							$("#storelocator-tab1").empty().append(html);
						}
                        
                        jQuery("#controltab1").click();

                        //*********
                    }
                });                
            }
        });
    }
    
    function createMapMarkerHtml(marker, html){
        var latlng = new GLatLng(parseFloat(marker.getAttribute("lat")), parseFloat(marker.getAttribute("lng")));
        var mapmarker = new GMarker(latlng, {title: getTitle(marker)});
        GEvent.addListener(	mapmarker, 
        					"click", 
        					function(){
            					mapmarker.openInfoWindowHtml(html, {maxWidth : 388});
        					});
        return mapmarker;
    }
    
    function generateHtmlForMarker(marker){

    	var favorite = marker.getAttribute("favorite");
        var insegna = marker.getAttribute("insegna");
    	var promolinklogged = "/promozioni-sconti/offerte/volantini.html";
    	var promolinkfavornotlogged = "/promozioni-sconti/offerte/volantini.html?group=" + escape(insegna);
        
        //variables used to set correct css classes
        var baloonclass;
        var formatoclass;
        var thisnumber;
        var balooncontent;
        if (insegna == "Carrefour") {
        	baloonclass = "balloon1";
        	formatoclass = "Ipermercato";
        	balooncontent = "Iper";
        	supermercatinumber++;
        	thisnumber = supermercatinumber;
        } else if (insegna == "Carrefour Market"){
        	baloonclass = "balloon2";
        	formatoclass = "Supermercato";
        	balooncontent = "Market";
        	ipermercatinumber++;
        	thisnumber = ipermercatinumber;
        } else {//Carrefour Express
        	baloonclass = "balloon3";
        	formatoclass = "Express";
        	balooncontent = "Express";
        	expressnumber++;
        	thisnumber = expressnumber;
        }
        var html;
        if (favorite != 'true') {
        	html = "<div class='resultat " + baloonclass + "' id='" + marker.getAttribute("codicePdv") + "'>" +
            			"<a class='aggiungi add' href='#' id='addToMyC4" + marker.getAttribute("codicePdv") + "'>Aggiungi in MyCarrefour</a>";
        } else {
        	html = "<div class='resultat " + baloonclass + "' id='" + marker.getAttribute("codicePdv") + "'>" +
            			"<a class='aggiungi remove' href='#' id='removeFromMyC4" + marker.getAttribute("codicePdv") + "'>Elimina da MyCarrefour</a>";
        }
        html += "<p class='balloon_legend'>" + balooncontent + "</p>" +
		        "<div class='result_text'>" +
		        	"<a href='" + marker.getAttribute("link") + "'>";
        if (insegna == "Carrefour"){
        	var nomecc = marker.getAttribute("name");
        	if (nomecc.indexOf("Centro Commerciale") == -1) {
        		nomecc = "Centro Commerciale " + nomecc;
        	}
        	html += nomecc + " - " + 
        			"<span class='" + formatoclass + "'>" +	marker.getAttribute("formato") + "</span>&nbsp;" + 
        			marker.getAttribute("insegna") + "&nbsp;" + marker.getAttribute("namePdv");
        } else {
        	html +=	"<span class='" + formatoclass + "'>" +	marker.getAttribute("formato") + "</span>&nbsp;" +
			marker.getAttribute("insegna") + " - " + marker.getAttribute("city") + "&nbsp;" + marker.getAttribute("address");        	
        }        
        
        html +=     "</a>" + 
        			"<p>" +
					        marker.getAttribute("address") +
					        ", " +
					        marker.getAttribute("civic") +
					        "<br />" +
					        marker.getAttribute("cap") +
					        " - " +
					        marker.getAttribute("city") +
					        "(" +
					        marker.getAttribute("province") +
					        ")" +
					        "<br />" +
					        marker.getAttribute("phone") +
			        "</p>" +
		        "</div>";
        if (favorite == 'true') {
        	html += "<p class='punto_preferito'><span/>Il tuo punto vendita preferito</p>";
        	promolink = promolinkfavornotlogged;
        } else if (logged) {
        	promolink = promolinklogged;
        } else {
        	promolink = promolinkfavornotlogged;
        }
        html += "<ul>" +
		        	"<li>" +
		        	"	<a class='trovar' href='#' onclick=\"findPath('" + marker.getAttribute("address") +
													        		"','" + marker.getAttribute("civic") + "','" + marker.getAttribute("cap") + "','" +
															        marker.getAttribute("city") + "','" + marker.getAttribute("province") +
															        "','" + marker.getAttribute("lat") +"','" +
															        marker.getAttribute("lng") +"'); return false\"" + ">" +
					        "<span></span>Trova il percorso" +
				        "</a>" +
			        "</li>" +
			        "<li><a class='news' href='" + marker.getAttribute("linkNews") +"'><span></span>News</a></li>" +
			        //"<li><a class='promozioni' href='/promozioni-sconti/offerte/volantini.html?group=all&codicePdv=" + marker.getAttribute("codicePdv") + "'><span></span>Promozioni</a></li>" +
			        "<li><a class='promozioni' href='" + promolink + "'><span></span>Promozioni</a></li>" +
		        "</ul>" +
	        "</div>";
        return html;
    }
});
