function dor_loading_start()
{
    $('#loading').show();
}

function dor_loading_end()
{
    $('#loading').hide();
}

function dor_redirect(uri)
{
    dor_loading_start();
    location.href = _DOR_URL + uri;
}

function dor_submitting()
{
    dor_loading_start();
    return true;
}

function dor_submitting_end()
{
    dor_loading_end();
}

function dor_datepicker(el)
{
    $(el).datepicker({
        changeMonth     : true,
        changeYear      : true,
        monthNames      : ["Janvier","F&eacute;vrier","Mars","Avril","Mai","Juin","Juillet","Ao&ucirc;t","Septembre","Octobre","Novembre","D&eacute;cembre"],
        closeText       : "Fermer",
        prevText        : "&#x3c;Pr&eacute;c",
        nextText        : "Suiv&#x3e;",
        currentText     : "Courant",
        monthNamesShort : ["Jan","F&eacute;v","Mar","Avr","Mai","Juin","Juil","Ao&ucirc;","Sep","Oct","Nov","D&eacute;c"],
        dayNames        : ["Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi"],
        dayNamesShort   : ["Dim","Lun","Mar","Mer","Jeu","Ven","Sam"],
        dayNamesMin     : ["Di","Lu","Ma","Me","Je","Ve","Sa"],
        dateFormat      : "dd/mm/yy",
        firstDay        : 1,
        yearRange       : '-80:0'
    });
}

var dor_recherche_map;
var dor_recherche_center;
var dor_recherche_zoom;
var dor_recherche_markers = {};

function dor_affRechercheMap(o)
{
    dor_recherche_center = new google.maps.LatLng(o.lat,o.lng);
    dor_recherche_zoom   = o.zoom || 12;
    var myOptions = {zoom: dor_recherche_zoom,center: dor_recherche_center,mapTypeId: google.maps.MapTypeId.ROADMAP};
    dor_recherche_map = new google.maps.Map(document.getElementById(o.target), myOptions);
    dor_addMarkerToMap({
        latlng  : dor_recherche_center,
        icon    : "marker_home.png",
        title   : o.title,
        map     : dor_recherche_map
    });

    var centerControlDiv = document.createElement('DIV');
    var centerControl = new dor_centerRechercheMapControl(centerControlDiv);
    centerControlDiv.index = 1;
    dor_recherche_map.controls[google.maps.ControlPosition.TOP_RIGHT].push(centerControlDiv);
}

function dor_centerRechercheMapControl(controlDiv) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map
  controlDiv.style.padding = '5px';

  // Set CSS for the control border
  var controlUI = document.createElement('DIV');
  controlUI.className = 'mapCenterPos';
  controlUI.title = 'Cliquez ici pour recentrer la carte sur votre position';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior
  var controlText = document.createElement('DIV');
  controlText.className = 'mapCenterText';
  controlText.innerHTML = 'Ma position';
  controlUI.appendChild(controlText);

  // Setup the click event listeners
  google.maps.event.addDomListener(controlUI, 'click', function() {
        dor_recherche_map.setCenter(dor_recherche_center);
        dor_recherche_map.setZoom(dor_recherche_zoom);
  });
}

function dor_addMarkerToMap(o)
{
    var latlng = o.latlng || new google.maps.LatLng(o.lat,o.lng);
    var icon = o.icon || 'marker_resto.png';
    //icon = _DOR_URL + 'images/' + icon;
    icon = 'http://www.directoresto.fr/images/' + icon;

    var marker = new google.maps.Marker({
        icon     : icon,
        position : latlng,
        map      : o.map,
        title    : o.title
    });

    var bulle = o.bulle || '';
    if( bulle )
    {
        google.maps.event.addListener(marker, 'click', function() {
            dor_infoWindowMap(o.map,marker,o.bulle);
        });
    }
    return marker;
}

function dor_clickRestoMapMarker(resto)
{
    var marker = dor_recherche_markers[resto];
    if( !marker ) return;
    dor_infoWindowMap(dor_recherche_map,marker,'resto-'+resto);
}

var dor_lastInfoWindow;

function dor_infoWindowMap(map,marker,content)
{
    if( dor_lastInfoWindow ) dor_lastInfoWindow.close();
    map.setCenter(marker.getPosition(),map.getZoom());
    if( $('#map-'+content).length !== 0 ) return;
    var infowindow = new google.maps.InfoWindow({
        content: '<div class="mapMarker" id="map-'+content+'" style="width:300px;height:150px;overflow-x:hidden;">Chargement...</div>'
    });
    dor_lastInfoWindow = infowindow;
    google.maps.event.addListener(infowindow, 'domready', function() {
        $('#map-'+content).load(_DOR_URL+'marker&m='+content+'&ajax');
    });
    infowindow.open(map,marker);
}

function dor_addRestoToSelection(ct,resto)
{
    $.ajax({
        url : _DOR_URL + 'user_selection&type=addresto&id='+resto+'&ajax',
        success : function(msg)
        {
            $(ct).attr('src' , _DOR_URL + 'images/heart_delete.png');
            $(ct).unbind("click");
            $(ct).bind("click",function(){dor_delRestoFromSelection('img.restosel'+resto,resto);});
    		$("#dialog_addRestoToSelection").dialog({
    			modal     : true,
    			autoOpen  : false,
    			draggable : false,
    			resizable : false,
    			/*show      : 'clip',
    			hide      : 'explode',*/
    			buttons: {
    				Ok: function() {
    					$(this).dialog('close');
    				}
    			}
    		}).dialog('open');
        }
    });
}

function dor_delRestoFromSelection(ct,resto)
{
	$('#dialog_delRestoFromSelection').dialog({
		modal     : true,
		autoOpen  : false,
		draggable : false,
		resizable : false,
		/*show      : 'clip',
		hide      : 'explode',*/
		buttons: {
			'Oui, je confirme' : function() {
			    dor_loading_start();
                $.ajax({
                    url : _DOR_URL + 'user_selection&type=delresto&id='+resto+'&ajax',
                    success : function(msg) {
                        if( ct === 0 )
                            dor_redirect('ma_selection');
                        else
                        {
                            dor_loading_end();
                            $(ct).attr('src' , _DOR_URL + 'images/heart_add.png');
                            $(ct).unbind("click");
                            $(ct).bind("click",function(){dor_addRestoToSelection('img.restosel'+resto,resto);});

                            $('#dialog_delRestoFromSelection').dialog('close');
                        }
                    }
                });
			},
			'Finalement, non' : function() {
				$(this).dialog('close');
			}
		}
	}).dialog('open');
}

function dor_errFormDialog(msg) {
    if( msg.length < 1 ) return;
    $('#dialog_errForm').html('<ul><li>' + msg.join('</li><li>') + '</li></ul>').dialog({
		modal     : true,
		draggable : false,
		resizable : false,
		autoOpen  : false,
		width     : 500,
		buttons: {
			Ok: function() {
				$(this).dialog('close');
			}
		}
    }).dialog('open');
}

function dor_bookmark() {
    var title = encodeURIComponent(document.title);
    var url   = document.URL;

    // if firefox
    if(window.sidebar) {
        window.sidebar.addPanel(title, url, "");
    }
    // elseif opera
    else if(window.opera && window.print) {
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    }
    // elseif IE
    else if(document.all) {
        window.external.AddFavorite(url, title);
    }
}

function dor_social_link(social) {
    var title = encodeURIComponent(document.title);
    var url   = encodeURIComponent(document.URL);

    var  o  = {};

    switch (social) {
        case 'favoris':
            document.write('<a href="#" onclick="dor_bookmark(); return false;" title="Favoris"><img src="' + _DOR_URL + 'images/social/favoris.png" alt="Favoris" />Favoris</a>');
            return;
            break;

        case 'facebook':
            o.name  = 'Facebook';
            o.url   = 'http://www.facebook.com/sharer.php?u=' + url + '&amp;t=' + title;
            break;

        case 'google':
            o.name  = 'Google';
            o.url   = 'http://google.com/bookmarks/mark?op=edit&amp;bkmk=' + url + '&amp;title=' + title;
            break;

        case 'yahoo':
            o.name  ='Yahoo! My Web';
            o.url   = 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=' + url + '&amp;t=' + title;
            break;

        case 'live':
            o.name  = 'Live';
            o.url   = 'https://favorites.live.com/quickadd.aspx?marklet=1&amp;mkt=en-us&amp;url=' + url + '&amp;title=' + title;
            break;

        case 'delicious':
            o.name  = 'Del.icio.us';
            o.url   = 'http://del.icio.us/post?url=' + url + '&amp;title=' + title;
            break;

        case 'digg':
            o.name  = 'Digg';
            o.url   = 'http://digg.com/submit?phase=2&amp;url=' + url + '&amp;title=' + title;
            break;

        case 'reddit':
            o.name  = 'Reddit';
            o.url   = 'http://reddit.com/submit?url=' + url + '&amp;title=' + title;
            break;

        case 'myspace':
            o.name  = 'MySpace';
            o.url   = 'http://www.myspace.com/index.cfm?fuseaction=postto&amp;t=' + title + '&amp;c=&amp;u=' + url;
            break;

        case 'twitter':
            o.name ='Twitter';
            o.url  ='http://twitter.com/home?status=' + url;
            break;

        case 'viadeo':
            o.name ='Viadeo';
            o.url  ='http://www.viadeo.com/shareit/share/?url=' + url + '&amp;title=' + title;
            break;

        case 'wikio':
            o.name ='Wikio';
            o.url  ='http://www.wikio.com/vote?newurl=' + url;
            break;

        case 'yoolink':
            o.name ='Yoolink';
            o.url  ='http://www.yoolink.fr/post/tag?f=aa&amp;url_value=' + url + '&amp;title=' + title;
            break;

        case 'linkedin':
            o.name ='LinkedIn';
            o.url  ='http://www.linkedin.com/shareArticle?mini=true&amp;url=' + url + '&amp;ro=false&amp;title=' + title;
            break;

        case 'netvibes':
            o.name ='Netvibes';
            o.url  ='http://www.netvibes.com/share?url=' + url + '&amp;title=' + title;
            break;

        case 'scoopeo':
            o.name ='Scoopeo';
            o.url  ='http://www.scoopeo.com/scoop/new?newurl=' + url + '&amp;title=' + title;
            break;

        case 'yahoobuzz':
            o.name ='Yahoo Buzz';
            o.url  ='http://buzz.yahoo.com/submit?submitUrl=' + url + '&amp;submitHeadline=' + title;
            break;

        default:
            return;
            break;
    }
    document.write('<a href="' + o.url + '" title="' + o.name + '" onclick="window.open(this.href); return false;"><img src="' + _DOR_URL + 'images/social/' + social + '.png" alt="' + o.name + '" />' + o.name + '</a>');
}

function dor_banClick(b)
{
    $.ajax({url : _DOR_URL + 'banclick&id='+b+'&ajax'});
}

function dor_justarrived() {
	$("#dialog_justarrived").dialog({
		modal     : true,
		autoOpen  : false,
		draggable : false,
		resizable : false,
		width     : 600
	}).dialog('open');
}

function dor_justarrived_close() {
    $("#dialog_justarrived").dialog('close');
}

function dor_afficherCharteAvis() {
    $("#dialog_charteAvis").dialog('destroy');
	$("#dialog_charteAvis").dialog({
		modal     : true,
		autoOpen  : true,
		draggable : false,
		resizable : false,
		width     : 850,
		height    : 550,
		buttons: {
			Ok: function() {
				$(this).dialog('close');
			}
		}
	});
}

function dor_ajouterUnAvis(resto) {
    $('#liste-avis').hide();
    $('#deposer-un-avis').load(_DOR_URL + 'avis_add&id='+resto+'&ajax');
}

function dor_ajouterUnAvis_submit()
{
    dor_submitting();
    $('#formAvisAdd .formInputError').removeClass('formInputError');
    var resto = $('#formAvisAdd input[name=avis_resto_id]').val();
    var o = {
        url      : _DOR_URL + 'avis_add&submit=1&id='+resto+'&ajax',
        dataType : 'json',
        success  : dor_ajouterUnAvis_callback
    };
    $(this).ajaxSubmit(o);
    return false;
}

function dor_ajouterUnAvis_creerCompte() {
    $('#avis-user-identification').hide();
    $('#avis-user-creation').show();
    $('#avis_user_mode').val('creation');
}

function dor_ajouterUnAvis_loginCompte() {
    $('#avis-user-identification').show();
    $('#avis-user-creation').hide();
    $('#avis_user_mode').val('login');
}

function dor_ajouterUnAvis_callback(data) {
    dor_submitting_end();

    if( data.success )
    {
        $('#deposer-un-avis').html('');
        $("#dialog_ajouterAvisOK").dialog('destroy');
    	$("#dialog_ajouterAvisOK").dialog({
    		modal     : true,
    		autoOpen  : true,
    		draggable : false,
    		resizable : false,
    		width     : 500,
    		buttons: {
    			Ok: function() {
    				$(this).dialog('close');
    				dor_loading_start();
    				var url = location.href;
    				url = url.replace('?deposer-un-avis','');
                    url = url.replace('#avis-creer-compte','');

    				location.href = url + '#avis';
    				/*location.href = '#avis';
    				location.reload();*/
    			}
    		}
    	});
    }
    else
    {
        if( data.errFields )
        {
            var msg = new Array();
            for( var f in data.errFields )
            {
                $('#formAvisAdd [name='+f+']').addClass('formInputError');
                if( data.errFields[f] != 1)
                    msg.push(data.errFields[f]);
            }
            dor_errFormDialog(msg);
        }
    }
}

function dor_removeErrorClsOnFocus(el) {
    $(el).removeClass('formInputError');
}

function dor_restoLnkAddAvis(resto) {
    //$('#resto_tabs').tabs('select',$('#resto_tabs').tabs('length'));
    // les tabs sont à l'envers ;)
    $('#resto_tabs').tabs('select',0);
    dor_ajouterUnAvis(resto);
}

function dor_showAvisDetail(avis) {
    $('#un_avis_detail_'+avis).toggleClass('avis_detail_visible');
}

function dor_votreResto() {
    $("#votre_resto").dialog('destroy');
	$("#votre_resto").dialog({
		modal     : true,
		autoOpen  : true,
		draggable : false,
		resizable : false,
		width     : 936,
		height    : 600,
		buttons: {
			Ok: function() {
				$(this).dialog('close');
			}
		}
	});
}
