
function showHideChooseCities() {
    $("#headerChooseCity").slideToggle();
}

function hideLandingDiv(){
    $("#messageLanding").slideUp();
    var expDate = new Date();
    expDate.setTime(expDate.getTime() + (30 * 24 * 3600 * 1000));
    document.cookie = "TwangooviewLandingMacau=true"+";expires=" + expDate.toGMTString();
}

function hideReferDiv(){
    $("#messageLanding").slideUp();
}

function valideSyntaxOfMail(strOfEmail){
    var place = strOfEmail.indexOf("@",1);
    var point = strOfEmail.indexOf(".",place+1);
    if ((place > -1)&&(strOfEmail.length >2)&&(point > 1)){
        return true;
    }
    else{
        return false;
    }
}

function openModalDialog(){
    $("#dialog").dialog({
        modal:true,
        resizable:false,
        buttons: {
            'Close' : function(){
                $(this).dialog('close');
            }
        },
        close : function(){
            resetModalDialog();
            $(this).dialog('destroy');
        }
    });
}

function resetModalDialog(){
    $("#dialog").attr('title', 'Loading');
    $("#dialog").attr('style', '');
    $("#dialog").html('Loading');
}
function fillModalError(){
    $('#dialog').attr('title', 'Error');
    $('#dialog').html('<p class="center">An internal error has occured</p>');
}

function test_email(my_email) {
    var new_string = new String(my_email);
    if (!new_string.match('^[-_\.0-9a-zA-Z]{1,}@[-_\.0-9a-zA-Z]{1,}[\.][0-9a-zA-Z]{2,}$')) {
        return false;
    } else {
        return true;
    }
}

function addCommentaireDeal(){
    var error = 0;
    var messageErreur = '';
    if( $('#formCommentaireMessage').val() == '' ) {
        messageErreur = '<p class="center bold">Your comment can\'t be blank</p>';
        error = 1;
    }

    if( error == 1 ) {
        $("#dialog").attr('title', 'Comments');
        $("#dialog").html(messageErreur);
		
        $("#dialog").dialog({
            modal:true,
            resizable:false,
            height:200,
            width:400,
            buttons: {
                'Ok' : function(){
                    $(this).dialog('close');
                }
            },
            close : function(){
                resetModalDialog();
                $(this).dialog('destroy');
            }
        });
    } else {
        $('#formCommentaire').submit();
    }
}

function openModalLogin(){
    var html = '<form id="formLogin" action="" name="formLogin" method="post">'
    + '<table width="100%">'
    + '<tr>'
    + '<td width="100">'
    + 'Email : '
    + '</td>'
    + '<td align="center">'
    + '<input type="text" id="formEmailValue" name="formEmailValue" style="width:180px;" />'
    + '</td>'
    + '</tr>'
    + '<tr>'
    + '<td width="100">'
    + 'Password : '
    + '</td>'
    + '<td align="center">'
    + '<input type="password" id="formPassValue" name="formPassValue" style="width:180px;" />'
    + '</td>'
    + '</tr>'
    + '</table>'
    + '</form>'
    + '<p id="messageErreur" class="center" style="display:none;">&nbsp;</p>'
    + '<p style="text-align:center"><a href="lost-password">Forgot your password ?</a></p>';
	
    $("#dialog").attr('title', 'Sign in');
    $("#dialog").html(html);
	
    $("#dialog").dialog({
        modal:true,
        resizable:false,
        width:400,
        buttons: {
            'Cancel' : function(){
                $(this).dialog('close');
            },
            'Submit' : function(){
                $("#formEmailValue").attr('style', 'width:180px;color:#000000;background:ffffff;');
                $("#formPassValue").attr('style', 'width:180px;color:#000000;background:ffffff;');
                $("#messageErreur").attr('style', 'display:none;');
                var email = $('#formEmailValue').val();
                var password = $('#formPassValue').val();
			
                if( email != '' && password != '' ) {
                    if(test_email(email)) {
                        $('#formLogin').attr('action', document.location);
                        $('#formLogin').submit();
                    } else {
                        $("#formEmailValue").attr('style', 'width:180px;color:#000000;background:#dbeff7;');
                        $("#messageErreur").attr('style', 'display:block;');
                        $("#messageErreur").html('<span style="font-weight:bold;color:#000000;">Invalid email!</span>');
                    }
                } else {
                    $("#formEmailValue").attr('style', 'width:180px;color:#000000;background:#dbeff7;');
                    $("#formPassValue").attr('style', 'width:180px;color:#000000;background:#dbeff7;');
                    $("#messageErreur").attr('style', 'display:block;');
                    $("#messageErreur").html('<span style="font-weight:bold;color:#000000;">Fill in the form.</span>');
                }
            }
        },
        close : function(){
            resetModalDialog();
            $(this).dialog('destroy');
        }
    });

}

function submitFormNewsletterSubscribe(landing){
    var error = false;
    var msgError = '';
	
    $("#dialog").html('<p class="center">Please wait...</p>');
	
    if ($("#newsletterEmail").val() == '' || (!valideSyntaxOfMail($("#newsletterEmail").val()))){
        error = true;
        msgError += '<p class="center">Please enter a valid email!</p>'
    }
	
    if (error == false){
        $.ajax({
            type: "POST",
            async: false,
            url: "ajax/newsletter.ajax.php?task=subscribe",
            data: "newsletterEmail="+$("#newsletterEmail").val(),
            success: function(msg){
                document.cookie = "TwangooNewsleterSubscribe=true";
                var tabReponse = msg.split('|@|');
                if(tabReponse[0] != 'ok') {//cas d'erreur
                    $("#dialog").html('<p class="center">'+ tabReponse[1] +'</p><input type="hidden" id="hiddenOk" value="'+tabReponse[2]+'" />');
                }
                else{
                    $("#dialog").html('<p class="center">You just register to Twangoo\'s newsletter.</p>');
                    $("#newsletterEmail").val('');
                }
            },
            failure: function(){
                $("#dialog").html('<p class="center">An internal error has occured</p>');
            }
        });
    }
    else {
        $("#dialog").html(msgError);
    }
	
    $("#dialog").attr('title', 'Newsletter');
	
    $("#dialog").dialog({
        modal:true,
        resizable:false,
        buttons: {
            'Close' : function(){
                $(this).dialog('close');
            }
        },
        close : function(){
            resetModalDialog();
            $(this).dialog('destroy');
        }
    });
}

function submitFormNewsletterLanding(){
    var error = false;
    var msgError = '';
	
    $("#dialog").html('<p class="center">Please wait...</p>');
	
    if ($("#newsletterEmail").val() == '' || (!valideSyntaxOfMail($("#newsletterEmail").val()))){
        error = true;
        msgError += '<p class="center">Please enter a valid email!</p>'
    }
	
    if (error == false){
        $.ajax({
            type: "POST",
            async: false,
            url: "ajax/newsletter.ajax.php?task=subscribe",
            data: "newsletterEmail="+$("#newsletterEmail").val()+"&city="+$("#newsletterCity").val()+"&newsletterRefer="+$("#newsletterRefer").val(),
            success: function(msg){
                document.cookie = "TwangooNewsleterSubscribe=true";
                var tabReponse = msg.split('|@|');
                if(tabReponse[0] != 'ok') {//cas d'erreur
                    $("#dialog").html('<p class="center">'+ tabReponse[1] +'</p><p class="center"><a href="deal">View the deal</a></p><input type="hidden" id="hiddenOk" value="'+tabReponse[2]+'" />');
                }
                else{
                    //Pour laffil et le tracking
                    if (tabReponse[4] == 3){
                        document.location.replace("affiliate-tracking,"+tabReponse[3]);
                    }
                    else {
                        document.location.replace("city,1");
                    }
                }
            },
            failure: function(){
                $("#dialog").html('<p class="center">An internal error has occured</p>');
            }
        });
    }
    else {
        $("#dialog").html(msgError);
    }
	
    $("#dialog").attr('title', 'Newsletter');
	
    $("#dialog").dialog({
        modal:true,
        resizable:false,
        buttons: {
            'Close' : function(){
                $(this).dialog('close');
            }
        },
        close : function(){
            resetModalDialog();
            $(this).dialog('destroy');
        }
    });
}

//A supprimer ?
function submitFormNewsletterSubscribe2(){
    var error = false;
    var msgError = '';
	
    if ($("#newsletterEmail2").val() == '' || (!valideSyntaxOfMail($("#newsletterEmail2").val()))){
        error = true;
        msgError += '<p class="center">Please enter a valid email!</p>'
    }
		
    if (error == false){
        $.ajax({
            type: "POST",
            url: "ajax/newsletter.ajax.php?task=subscribe",
            data: "newsletterEmail="+$("#newsletterEmail2").val()+"&newsletterCity="+$("#newsletterCity2").val(),
            success: function(msg){
                var tabReponse = msg.split('|@|');
                if(tabReponse[0] != 'ok') {//cas d'erreur
                    $("#dialog").html('<p class="center">'+ tabReponse[1] +'</p>');
                }
                else{
                    $("#dialog").html('<p class="center">You just register to Twangoo\'s newsletter.</p>');
                    $("#newsletterEmail2").val('');
                }
            },
            failure: function(){
                $("#dialog").html('<p class="center">An internal error has occured</p>');
            }
        });
    }
    else {
        $("#dialog").html(msgError);
    }
	
    $("#dialog").attr('title', 'Suscribe to the newsletter');
    openModalDialog();
}

function loadModalCGV(){
    $.ajax({
        type: "POST",
        url: 'ajax/common.ajax.php?task=getPageCMSContent',
        data:'pageid=4',
        success: function(msg){
            var tabReponse = msg.split('|@|');
            if(tabReponse[0] == 'ok') {
                $("#dialog").html('<div style="heigth:400px;overflow:auto;">'+tabReponse[1]+'</div>');
                $("#dialog").dialog({
                    modal: true,
                    resizable: false,
                    title: 'Terms',
                    width: 700,
                    height: 400,
                    buttons: {
                        "Close": function() {
                            $(this).dialog("close");
                        }
                    },
                    close : function(){
                        resetModalDialog();
                        $(this).dialog('destroy');
                    }
                });
            }
            else{
                fillModalError();
                openModalDialog();
            }
        },
        failure: function(){
            fillModalError();
            openModalDialog();
        }
    });
}

function loadPageGDC(pageId){
    $.ajax({
        type: "POST",
        url: 'ajax/common.ajax.php?task=getPageCMSContent',
        data:'pageid='+pageId,
        success: function(msg){
            var tabReponse = msg.split('|@|');
            if(tabReponse[0] == 'ok') {
                $("#dialog").html('<div style="heigth:400px;overflow:auto;">'+tabReponse[1]+'</div>');
                $("#dialog").dialog({
                    modal: true,
                    resizable: false,
                    title: '',
                    width: 700,
                    height: 400,
                    buttons: {
                        "Close": function() {
                            $(this).dialog("close");
                        }
                    },
                    close : function(){
                        resetModalDialog();
                        $(this).dialog('destroy');
                    }
                });
            }
            else{
                fillModalError();
                openModalDialog();
            }
        },
        failure: function(){
            fillModalError();
            openModalDialog();
        }
    });
}
//http://www.unwrongest.com/projects/limit/
(function($){
    $.fn.extend({
        limit:function(limit,element){
            var interval,f;
            var self=$(this);
            $(this).focus(function(){
                interval=window.setInterval(substring,100)
            });
            $(this).blur(function(){
                clearInterval(interval);
                substring()
            });
            substringFunction="function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
            if(typeof element!='undefined')substringFunction+="if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}";
            substringFunction+="}";
            eval(substringFunction);
            substring()
        }
    })
})(jQuery);

window.onload = function() {
	
    //initFB();
	
    if( $('#formCommentaireMessage').length != 0 ) {
        $('#formCommentaireMessage').limit('255','#charsLeft');
    }
	
}

function initFB() {
    FB_RequireFeatures(["XFBML"], function(){
        FB.init("6dba329b58109a6dd699a85f36e1ed55", "lib/facebook/xd_receiver.htm", {
            permsToRequestOnConnect:"read_stream,publish_stream,offline_access",
            "reloadIfSessionStateChanged":true
        });
    });
}

function facebook_prompt_permission(permission) {
    FB.ensureInit(function() {
        FB.Connect.showPermissionDialog(permission);
    });
}

function logout() {
    document.location.href="logout,user"
}

function callPublish(msg, attachment, action_link) {
    FB.ensureInit(function () {
        FB.Connect.streamPublish('', attachment, action_link);
    });
}

/*
 * Show the feed form. This would be typically called in response to the
 * onclick handler of a "Publish" button, or in the onload event after
 * the user submits a form with info that should be published.
 *
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
    // Load the feed form
    FB.ensureInit(function() {
        FB.Connect.showFeedDialog(form_bundle_id, template_data);
    //FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);
    });
}

/*
 * If a user is not connected, then the checkbox that says "Publish To Facebook"
 * is hidden in the "add run" form.
 *
 * This function detects whether the user is logged into facebook but just
 * not connected, and shows the checkbox if that's true.
 */
function facebook_show_feed_checkbox() {
    FB.ensureInit(function() {
        FB.Connect.get_status().waitUntilReady(function(status) {
            if (status != FB.ConnectState.userNotLoggedIn) {
                // If the user is currently logged into Facebook, but has not
                // authorized the app, then go ahead and show them the feed dialog + upsell
                checkbox = ge('publish_fb_checkbox');
                if (checkbox) {
                    checkbox.style.visibility = "visible";
                }
            }
        });
    });
}

function detectNavig () {
    if (navigator.userAgent.indexOf('MSIE 6')!=-1) {
        $("#dialog").html('Our site is not optimised for your browser. We recommend you to update your browser to a <a href="http://www.microsoft.com/france/windows/internet-explorer/" target="_blank">later version</a> or use another browser such as <a href="http://www.getfirefox.com" target="_blank">Firefox</a>, <a href="http://www.apple.com/fr/safari/" target="_blank">Safari</a>, <a href="href="http://www.opera.com/" target="_blank">Opera</a>...');
							
        $("#dialog").dialog({
            modal: true,
            resizable: false,
            title: 'Warning!',
			
            width: 400,
            buttons: {
                "Close": function() {
                    $(this).dialog("close");
                }
            },
            close : function(){
                resetModalDialog();
                $(this).dialog('destroy');
            }
        });
    }
};

function openModalMeteo(){
    $("#dialog").attr('title', 'M&eacute;t&eacute;o');
    $("#dialog").html('<p class="center">Chargement de la m&eacute;t&eacute;o</p>');
    $("#dialog").dialog({
        modal: true,
        resizable: false,
        width: 600,
        buttons: {
            "Close": function() {
                $(this).dialog("close");
            }
        },
        close : function(){
            resetModalDialog();
            $(this).dialog('destroy');
        }
    });
    $.ajax({
        type: "GET",
        url: "ajax/meteo.ajax.php",
        success: function(msg){
            var tabReponse = msg.split('|@|');
            if(tabReponse[0] != 'ok') {//cas d'erreur
                $("#dialog").html('<p class="center">La m&eacute;t&eacute;o ne peut pas &ecirc;tre affich&eacute;e.</p>');
            }
            else{
                $("#dialog").dialog( "option" , 'title' , tabReponse[2] );
                $("#dialog").html('<p class="center">'+ tabReponse[1] +'</p>');
            }
        },
        failure: function(){
            $("#dialog").html('<p class="center">An internal error has occured</p>');
        }
    });
}


function handleErrors(){
    var html = '<p class="center">';
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        html += 'Une des adresses n\'a pas &eacute;t&eacute; trouv&eacute;e.';
    else html += 'L\itin&eacute;n&eacute;raire ne peut pas &ecirc;tre calcul&eacute;.';

    html += '</p>';
	
    $("#dialog").html(html);
    $("#dialog").attr('title', 'Error');
    openModalDialog();
}

function checkDirection(fromStreet, fromZipCode, fromCity) {
    var error = false;
    var txtError = '';
    if (fromStreet == ''){
        error = true;
        txtError += '<p class="center">Veuillez saisir un nom de rue.</p>';
    }
    if (fromZipCode == ''){
        error = true;
        txtError += '<p class="center">Veuillez saisir un code postal.</p>';
    }
    if (fromCity == ''){
        error = true;
        txtError += '<p class="center">Veuillez saisir une ville.</p>';
    }
	
    if (error == false){
        return true;
    }
    else {
        $("#dialog").html(txtError);
        $("#dialog").attr('title', 'Error');
        openModalDialog();
        return false;
    }
}

function toogleCity(){
    $('#villeListeContainer').slideToggle();
}

function toogleFaq(id){
    $('#'+id).slideToggle();
}

function IsNumeric(sText){
    //v�rifie si la chaine envoy�e est de type num�rique
    /*var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	
	for (i = 0; i < sText.length ; i++) {
		Char = sText[i];
		if (ValidChars.indexOf(Char) == -1){
			IsNumber = false;
		}
	}
	return IsNumber;*/
    return !isNaN(parseFloat(sText)) && isFinite(sText);

}

function submitOverlayFormNewsletter(){
    var error = false;
    var msgError = '';

    parent.$.fancybox.showActivity();

    if ($("#overlayEmail").val() == '' || (!valideSyntaxOfMail($("#overlayEmail").val()))){
        error = true;
        msgError += 'Please enter a valid email!'
    }

    if (error == false){
        $.ajax({
            type: "POST",
            async: false,
            url: "ajax/newsletter.ajax.php?task=subscribe",
            data: "newsletterRefer=10&newsletterEmail="+$("#overlayEmail").val()+"&newsletterCity="+$("#overlayCity").val(),
            success: function(msg){
                var tabReponse = msg.split('|@|');
                if(tabReponse[0] != 'ok') {//cas d'erreur
                    $("#overlay-error").html(''+ tabReponse[1] +'<input type="hidden" id="hiddenOk" value="'+tabReponse[2]+'" />');
                } else {
                    $.cookie('TwangooNewsleterSubscribe', true, {
                        expires: 99999
                    });
                    parent.$.fancybox.close();
                }
            },
            failure: function(){
                $("#overlay-error").html('An internal error has occured. Please retry.');
            }
        });
    }
    else {
        $("#overlay-error").html(msgError);
    }


    parent.$.fancybox.hideActivity();

}

function initFancyBox(){
    $("#overlay-iframe").fancybox({
        'type'	: 'iframe',
        'href'	: 'overlay-subscribe',
        'width'	: 655,
        'height'	: 355,
        'padding'   : 0,
        'hideOnOverlayClick' : false

    });
    
    if(isLogin)$.cookie('TwangooNewsleterSubscribe', true, {
        expires: 9999
    });

    if ( !$.cookie('first_visit') && !$.cookie('TwangooNewsleterSubscribe')) {
        $("#overlay-iframe").trigger('click');
        $.cookie('first_visit', true, {
            expires: 7
        });
    }
}

