/**
 * Mobile redirect script by Xander Ladage
 * (c) 2011 - Xander Ladage for GX Software (http://www.gxsoftware.com)
 * All rights reserved.
 * Usage or copying of (parts of this) script is not allowed without explicit approval of the author or GX Software.
 */


/*JSlint.com validation*/
/*global alert, document, escape, navigator, unescape, window*/
/*jslint globalstrict: true, sloppy: true, indent: 4*/


/**
 * Mobile redirect array contains arrays containing a device identifier and a redirect url.
 * E.a. ['ipad', 'http://ipad.domain.com']
 * These are registered using the addToMobileRedirectArray(identifier, url) function.
 */
var MobileRedirectArray = [];


/**
 * Default expiration for non-session-only cookies
 */
var CookieExpires = 60 * 60 * 24 * 40; // 40 days


/**
 * Set cookie and cookie value.
 * @param name name of the cookie to set
 * @param value value of the cookie to set
 * @expires expiration in seconds! (may be negative for cookie removal purposes, or 0 or null for session-only cookies)
 */
function setMobileRedirectCookie(name, value, expires) {
    var expire = new Date();
    if (expires === '' || expires === null || expires === 0) {
        // Set session cookie data
        document.cookie = name + '=' + escape(value) + ';path=/';
    } else {
        // Convert seconds to milliseconds
        expires = expires * 1000;
        // Create new date object using expiration
        expire.setTime(expire.getTime() + expires);
        // Set normal cookie data
        document.cookie = name + '=' + escape(value) + ';path=/;expires=' + expire.toUTCString();
    }
}


/**
 * Get cookie value.
 * @param name name of the cookie to get value from
 * @return cookie value or null if cookie was not found
 */
function getMobileRedirectCookie(name) {
    var c_start, c_end, result;
    result = null;
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(name + "=");
        if (c_start !== -1) {
            c_start = c_start + name.length + 1;
            c_end = document.cookie.indexOf(';', c_start);
            if (c_end === -1) {
                c_end = document.cookie.length;
            }
            result = unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return result;
}


/**
 * Add a mobile redirect to the global redirect array.
 * @param identifier identifier of mobile redirect
 * @param url url of mobile redirect
 */
function addToMobileRedirectArray(identifier, url) {
    var i, redirectExists;
    redirectExists = false;
    for (i = 0; i < MobileRedirectArray.length; i = i + 1) {
        if (MobileRedirectArray[i][0] === identifier) {
            redirectExists = true;
            // Update existing redirect entry
            MobileRedirectArray[i] = [identifier, url];
        }
    }
    if (!redirectExists) {
        MobileRedirectArray[MobileRedirectArray.length] = [identifier, url];
    }
}


/**
 * Get redirect identifier based on user agent.
 * Redirect id may be empty.
 * @return the identifier for the redirect (or empty string)
 */
function getRedirectIdForUserAgent() {
    var redirectid = 'desktop';
    // OS driven selector
    if (navigator.userAgent.match(/mobi/i) || navigator.userAgent.match(/symbian/i) || navigator.userAgent.match(/bada/i) || navigator.userAgent.match(/android/i)) {
        redirectid = 'mobile';
    }
    // Manufacturer driven selector
    if (navigator.userAgent.match(/nokia/i) || navigator.userAgent.match(/sony/i) || navigator.userAgent.match(/samsung/i) || navigator.userAgent.match(/htc/i) || navigator.userAgent.match(/blackberry/i)) {
        redirectid = 'mobile';
    }
    // Operator driven selector
    if (navigator.userAgent.match(/t-mobile/i) || navigator.userAgent.match(/vodafone/i) || navigator.userAgent.match(/kpn/i) || navigator.userAgent.match(/hi/i)) {
        redirectid = 'mobile';
    }
    // Overrule mobile browser (advanced browsers will result in non-mobile webpage)
    if (navigator.userAgent.match(/Firefox/i) || navigator.userAgent.match(/Chrome/i)) {
        redirectid = 'desktop';
    }
    // Check for iPhone
    if (navigator.userAgent.match(/iPhone/i)) {
        redirectid = 'iphone';
    }
    // Check for iPad
    if (navigator.userAgent.match(/iPad/i)) {
        redirectid = 'ipad';
    }
    return redirectid;
}


/**
 * Get redirect url for some redirect identifier.
 * Redirect url may be empty.
 * @param redirectid the redirect indentifier to get url from
 * @return the redirect url for this identifier (or empty string)
 */
function getRedirectUrlForId(redirectid) {
    var i, redirecturl;
    redirecturl = '';
    for (i = 0; i < MobileRedirectArray.length; i = i + 1) {
        if (MobileRedirectArray[i][0] === redirectid) {
            redirecturl = MobileRedirectArray[i][1];
        }
    }
    return redirecturl;
}


/**
 * Handle the redirect based in redirectid.
 * @param redirectid redirect id to get url for
 */
function handleRedirect(redirectid) {
    var redirecturl = getRedirectUrlForId(redirectid);
    setMobileRedirectCookie('mobileredirectsession', 'mobileredirectsession', 0);
    setMobileRedirectCookie('mobileredirectid', redirectid, CookieExpires);
    // Redirect, prevent recursive redirects
    if (redirecturl !== '' && redirecturl !== window.location.href) {
        window.location = redirecturl;
    }
}


/**
 * Store visitor desktop choice.
 */
function storeChoiceDesktop() {
    handleRedirect('desktopwebsite');
}


/**
 * Store visitor mobile choice.
 */
function storeChoiceMobile() {
    handleRedirect('mobilewebsite');
}


/**
 * Check for cookie support.
 * Try to set a non-session cookie, if it returns null we know cookies are not supported.
 * @return boolean indicating if cookies are supported
 */
function checkCookieSupport() {
    setMobileRedirectCookie('testcookiesupport', 'testcookiesupport', 1);
    if (getMobileRedirectCookie('testcookiesupport') === null) {
        // Cookies are not supported
        return false;
    } else {
        // Remove (expire) test cookie first
        setMobileRedirectCookie('testcookiesupport', 'testcookiesupport', -1);
        return true;
    }
}


/**
 * Check for mobile redirect.
 * If no session cookie is found, get redirect url based on cookie value (if present) or useragent.
 */
function initMobileRedirect() {
    var redirectid = null;
    if (getMobileRedirectCookie('mobileredirectsession') === null) {
        // We have no session cookie, if cookies are not supported, do nothing!
        // We can not do anithing because redirect will always be fired if i.e. a visitor checks the homepage
        if (!checkCookieSupport()) {
            return;
        }
        // Cookies are supported, so we need to handle the redirect
        if (getMobileRedirectCookie('mobileredirectid') === null) {
            // No previous choice has been stored, get target by user agent
            redirectid  = getRedirectIdForUserAgent();
        } else {
            // Visitor has choosen, get target by stored user choice
            redirectid  = getMobileRedirectCookie('mobileredirectid');
        }
        handleRedirect(redirectid);
    }
}

