$(document).ready(function() {
    $("#autoCompleteInput").autocomplete(window.location.protocol + '//' + window.location.host + '/pages/magasins/magasins-autocomplete.aspx', {
        width: 300,
        autoFill: false,
        minChars: 2,
        formatItem: formatItem,
        formatResult: formatResult,
        matchContains: true
    });

    function formatItem(row) {
        return row[0];
    }

    function formatResult(row) {
        return row[0].replace(/(<.+?>)/gi, '');
    }

    //Lien affecter un magasin
    $("#autoCompleteInput").result(function(event, data, formatted) {
        $(".liste_event").empty();
        GetStoresInformation(data[1]);
    });
});

function LoadModalStore(ID) {
    $.ajax(
				{
				    type: "GET",
				    url: String.format('/pages/cookies/SetCookie.aspx?idstore={0}&mod=true', ID),
				    success: function(data, status) {
				        self.parent.GetMagasin();
				        self.parent.tb_remove();
				    }

				});

}

function GetStoresInformation(ID) {
    var idx = 1;
    $.get(
			window.location.protocol + "//" + window.location.host + "/pages/magasins/magasin-xml.aspx?idstore=" + ID,
			function(xml) {
			    $(".liste_event").empty();
			    $(xml).find('Magasin').each(function() {
			        var mag_name = $(this).children('Name').text();
			        if ($(this).children('Name').text().length > 22)
			            mag_name = $(this).children('Name').text().substr(0, 22) + "...";

			        if (idx == 1) {
			            $('.liste_event').append(String.format('<a href="#" id="liste_horaire_{1}" class="liste_horaire selectmag"> {0} <span class="num_mag">{1}</span></a>',
														$(this).children('Name').text(),
														idx
														));
			        }
			        else {
			            $('.liste_event').append(String.format('<a href="#" id="liste_horaire_{1}" class="liste_horaire"> {0} <span class="num_mag">{1}</span></a>',
														    mag_name,
														    idx
														    ));
			        }

			        var now = new Date();
			        var dhui = now.getDay();
			        horaire = "non applicable";
			        switch (dhui.toString()) {
			            case "0":
			                horaire = $(this).children('HoraireOuvertureDimanche').text();
			                break;
			            case "1":
			                horaire = $(this).children('HoraireOuvertureLundi').text();
			                break;
			            case "2":
			                horaire = $(this).children('HoraireOuvertureMardi').text();
			                break;
			            case "3":
			                horaire = $(this).children('HoraireOuvertureMercredi').text();
			                break;
			            case "4":
			                horaire = $(this).children('HoraireOuvertureJeudi').text();
			                break;
			            case "5":
			                horaire = $(this).children('HoraireOuvertureVendredi').text();
			                break;
			            case "6":
			                horaire = $(this).children('HoraireOuvertureSamedi').text();
			                break;
			        }
			        var urlvar;
			        if (window.location.search != "") {
			            longueur = window.location.search.length - 1;
			            data = window.location.search.substr(1, longueur);
			            donnees = data.split("&");
			            urlvar = new Array();
			            urlvarnum = new Array();
			            for (var i = 0; i < donnees.length; i++) {
			                position = donnees[i].indexOf("=");
			                variable = donnees[i].substr(0, position);
			                pos = position + 1;
			                valeur = decodeURI(donnees[i].substr(pos, donnees[i].length));
			                while (valeur.search(/\+/) != -1)
			                    valeur = valeur.replace(/\+/, " ");
			                urlvar[variable] = valeur;
			                urlvarnum[i] = valeur;
			            }
			        }
			        var chaine = '<div id="liste_detail_{4}" class="liste_detail"><p><b>{0}<br />{1} {2}<br /></b></p><div class="adresse_mag">Tel. : {3}<br />Fax : {7}</div><a href="/pages/magasins/magasin-geant-casino-{8}-{5}.aspx" class="lien_vert" style="font-weight:bold;">Voir les d&#233;tails</a><div class="clear"></div><br /><p><b>Aujourd hui : </b>{6}</p> <div id="magfav_{5}"></div> </div><div id="liste_detail_bas_{4}" class="liste_detail_bas"></div>';
			        if (urlvar != null) {
			            if (urlvar['modal']) {
			                chaine = '<div id="liste_detail_{4}" class="liste_detail"><p><b>{0}<br />{1} {2}<br /></b></p><div class="adresse_mag">Tel. : {3}<br />Fax : {7}</div><div class="clear"></div><br /><p><b>Aujourd hui : </b>{6}</p> <div id="magfav_{5}"></div> </div><div id="liste_detail_bas_{4}" class="liste_detail_bas"></div>';
			            }
			            if (urlvar['mod']) {
			                chaine = '<div id="liste_detail_{4}" class="liste_detail"><p><b>{0}<br />{1} {2}<br /></b></p><div class="adresse_mag">Tel. : {3}<br />Fax : {7}</div><div class="clear"></div><br /><p><b>Aujourd hui : </b>{6}</p> <div id="magfav_{5}"></div> </div><div id="liste_detail_bas_{4}" class="liste_detail_bas"></div>';
			            }
			            if (urlvar['keepThis']) {
			                chaine = '<div id="liste_detail_{4}" class="liste_detail"><p><b>{0}<br />{1} {2}<br /></b></p><div class="adresse_mag">Tel. : {3}<br />Fax : {7}</div><div class="clear"></div><br /><p><b>Aujourd hui : </b>{6}</p> <div id="magfav_{5}"></div> </div><div id="liste_detail_bas_{4}" class="liste_detail_bas"></div>';
			            }
			        }
			        $('.liste_event').append(String.format(chaine,
														$(this).children('Adresse').children('Line1').text(),
														$(this).children('Adresse').children('CodePostale').text(),
														$(this).children('Adresse').children('Ville').text(),
														$(this).children('Adresse').children('Telephone').text(),
														idx,
														$(this).children('CodeMagasin').text(),
														horaire,
														$(this).children('Adresse').children('Fax').text(),
														$(this).children('UrlName').text()
														));
			        var qs = new Querystring()
			        var idpromo = qs.get('idpromotion');
			        var returnUrl = qs.get('returnUrl');
			        var modal = qs.get('keepThis');
			        var returnUrlRatachement = qs.get('returnUrlRatachement');
			        if (idpromo == null) {
			            if (returnUrlRatachement != null) {
			                $('#magfav_' + $(this).children('CodeMagasin').text()).append(String.format('<p><b>Mon magasin pr&eacute;f&eacute;r&eacute;?</b> <a href="/pages/cookies/SetCookie.aspx?idstore={0}&returnUrl={1}"><img src="/Style%20library/images/magasins/bouton_enregistrer.gif"/></a></p>', $(this).children('CodeMagasin').text(), returnUrlRatachement + $(this).children('CodeMagasin').text()));
			            }
			            else if (returnUrl == null) {
			                if (modal == null) {
			                    $('#magfav_' + $(this).children('CodeMagasin').text()).append(String.format('<p><b>Mon magasin pr&eacute;f&eacute;r&eacute;?</b> <a href="/pages/cookies/SetCookie.aspx?idstore={0}&returnurl=/pages/magasins/magasin-geant-casino-{1}-{0}.aspx"><img src="/Style%20library/images/magasins/bouton_enregistrer.gif"/></a></p>', $(this).children('CodeMagasin').text(), $(this).children('UrlName').text()));
			                    //   /pages/magasins/magasin-geant-casino-Clermont-Ferrand-CG815.aspx
			                }
			                else {
			                    $('#magfav_' + $(this).children('CodeMagasin').text()).append(String.format('<p><b>Mon magasin pr&eacute;f&eacute;r&eacute;?</b> <a onclick="LoadModalStore(\'{0}\');"><img src="/Style%20library/images/magasins/bouton_enregistrer.gif"/></a></p>', $(this).children('CodeMagasin').text()));
			                }
			            }
			            else {
			                $('#magfav_' + $(this).children('CodeMagasin').text()).append(String.format('<p><b>Mon magasin pr&eacute;f&eacute;r&eacute;?</b> <a href="/pages/cookies/SetCookie.aspx?idstore={0}&returnUrl={1}"><img src="/Style%20library/images/magasins/bouton_enregistrer.gif"/></a></p>', $(this).children('CodeMagasin').text(), returnUrl));
			            }

			        }
			        else {
			            $('.liste_event').append(String.format('<p><b>Mon magasin pr&eacute;f&eacute;r&eacute;?</b> <a href="/pages/cookies/SetCookie.aspx?idstore={0}&idpromotion={1}"><img src="/Style%20library/images/magasins/bouton_enregistrer.gif"/></a>', $(this).children('CodeMagasin').text(), idpromo));
			        }
			        idx++;
			    });
			    $(".liste_detail:not(:first)").hide();
			    $(".liste_detail_bas:not(:first)").hide();
			    $("#liste_detail_1").show();   /* forcer pour IE */
			    $(".liste_horaire").click(function() {

			        var lien = ($(this).attr('id'));
			        var chaine = lien.split("_");

			        //Close all boxes first
			        $(".liste_detail").hide("slow");
			        $(".liste_detail_bas").hide("show");
			        $(".liste_horaire").removeClass("selectmag");


			        $("#liste_detail_" + chaine[2] + ":visible").hide("slow");
			        $("#liste_detail_" + chaine[2] + ":hidden").show("slow");

			        $("#liste_detail_bas_" + chaine[2] + ":visible").hide("show");
			        $("#liste_detail_bas_" + chaine[2] + ":hidden").show("slow");


			        $(this).toggleClass('selectmag');

			        return false;

			    });
			}
		);
}