﻿function moBistro_getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);

    if (qs == null)
        return default_;
    else
        return qs[1];
}

function moBistro_getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function moBistro_setCookie(c_name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function moBistro_detect_mobile_device(restaurantId, url, ignoreParameter) {
    if(restaurantId == undefined || restaurantId == null || restaurantId.length == 0) {
        return;
    }
     
    if (ignoreParameter != undefined && ignoreParameter != null && ignoreParameter.length > 0) {
        // A Ignore parameter is defined to indicate that
        // mobile detect should not take place if this
        // parameter is present

        var ignoreParameterValue = moBistro_getQuerystring(ignoreParameter, null);
        if (ignoreParameterValue != null) {
            // Ignoreparameter exists so return
            return;
        }
    }

    if (url == undefined || url == null || url.length == 0) {
        url = "http://m.moBistro.com/DetectMobileJavaScript";
    }
    
    //Check if there is a QueryString parameter set
    //which may be set if the sending website presents an option
    //to force to mobile version

    var useMobile = moBistro_getQuerystring("UseMobile", null);
    
    if (useMobile == null || useMobile.length == 0) {
        // If no QueryString parameter then check cookies    
        useMobile = moBistro_getCookie("UseMobile");
    }
    
    if (useMobile != null && useMobile.length > 0)
    {
        moBistro_setCookie("UseMobile", useMobile, null);
        if (useMobile == '0' || useMobile.toLowerCase() == 'false') {
            return;
        }
    }

    url = url + "?restaurantId=" + restaurantId;
       
    document.write(unescape("%3Cscript src='" + url + "' type='text/javascript'%3E%3C/script%3E"));
}