// According to RFC 3986, only characters from a set of reserved and a set
// of unreserved characters are allowed in a URL:
var unreserved = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~";
var reserved = "!*'();:@&=+$,/?%#[]";
var allowed = unreserved + reserved;
var hexchars = "0123456789ABCDEFabcdef";

// --------------------------------- Encoding -------------------------------
// This function returns a percent sign followed by two hexadecimal digits.
// Input is a decimal value not greater than 255.


function gethex(decimal) {
    return "%" + hexchars.charAt(decimal >> 4) + hexchars.charAt(decimal & 0xF);
}


function decode(value2Decode, decodeType) {
    // Some variables:
    var encoded = value2Decode;
    var decoded = "";
    // Remember characters that are not allowed in a URL:
    var notallowed = "";
    // Remember illegal percent encoding:
    var illegalencoding = "";

    // ---------------- If ASCII character encoding was chosen: ----------------
    if (decodeType == "ascii") {
        var i = 0;
        while (i < encoded.length) {
            var ch = encoded.charAt(i);
            // Check for percent-encoded string:
            if (ch == "%") {
                // Check if percent-encoded string represents an ASCII character:
                if (getdec(encoded.substr(i, 3)) < 128) {
                    decoded = decoded + unescape(encoded.substr(i, 3));
                } else {
                    decoded = decoded + encoded.substr(i, 3);
                    illegalencoding = illegalencoding + encoded.substr(i, 3) + " ";
                }
                i = i + 3;
            } else {
                // Check if character is an allowed character:
                if (allowed.indexOf(ch) == -1) notallowed = notallowed + ch + " ";
                decoded = decoded + ch;
                i++;
            }
        }

        // Write result:
        return decoded;

        // Display warning message if necessary:
        var warning = "";
        if (notallowed != "") warning = warning + "Characters not allowed in a URL:\n" + notallowed + "\n\n";
        if (illegalencoding != "") warning = warning + "Illegal percent-encoding (for ASCII):\n" + illegalencoding + "\n\n";
        if (warning != "") alert("Warning: Illegal characters/strings in encoded text!\n\n" + warning);
    }

    // ---------------- If UTF-8 character encoding was chosen: ----------------
    if (decodeType == "utf8") {
        // UTF-8 bytes from left to right:
        var byte1, byte2, byte3, byte4 = 0;

        var i = 0;
        while (i < encoded.length) {
            var ch = encoded.charAt(i);
            // Check for percent-encoded string:
            if (ch == "%") {

                // Check for legal percent-encoding of first byte:
                if (getdec(encoded.substr(i, 3)) < 255) {

                    // Get the decimal values of all (potential) UTF-bytes:
                    byte1 = getdec(encoded.substr(i, 3));
                    byte2 = getdec(encoded.substr(i + 3, 3));
                    byte3 = getdec(encoded.substr(i + 6, 3));
                    byte4 = getdec(encoded.substr(i + 9, 3));

                    // Check for one byte UTF-8 character encoding:
                    if (byte1 < 128) {
                        decoded = decoded + String.fromCharCode(byte1);
                        i = i + 3;
                    }

                    // Check for illegal one byte UTF-8 character encoding:
                    if (byte1 > 127 && byte1 < 192) {
                        decoded = decoded + encoded.substr(i, 3);
                        illegalencoding = illegalencoding + encoded.substr(i, 3) + " ";
                        i = i + 3;
                    }

                    // Check for two byte UTF-8 character encoding:
                    if (byte1 > 191 && byte1 < 224) {
                        if (byte2 > 127 && byte2 < 192) {
                            decoded = decoded + String.fromCharCode(((byte1 & 0x1F) << 6) | (byte2 & 0x3F));
                        } else {
                            decoded = decoded + encoded.substr(i, 6);
                            illegalencoding = illegalencoding + encoded.substr(i, 6) + " ";
                        }
                        i = i + 6;
                    }

                    // Check for three byte UTF-8 character encoding:
                    if (byte1 > 223 && byte1 < 240) {
                        if (byte2 > 127 && byte2 < 192) {
                            if (byte3 > 127 && byte3 < 192) {
                                decoded = decoded + String.fromCharCode(((byte1 & 0xF) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F));
                            } else {
                                decoded = decoded + encoded.substr(i, 9);
                                illegalencoding = illegalencoding + encoded.substr(i, 9) + " ";
                            }
                        } else {
                            decoded = decoded + encoded.substr(i, 9);
                            illegalencoding = illegalencoding + encoded.substr(i, 9) + " ";
                        }
                        i = i + 9;
                    }

                    // Check for four byte UTF-8 character encoding:
                    if (byte1 > 239) {
                        if (byte2 > 127 && byte2 < 192) {
                            if (byte3 > 127 && byte3 < 192) {
                                if (byte4 > 127 && byte4 < 192) {
                                    decoded = decoded + String.fromCharCode(((byte1 & 0x7) << 18) | ((byte2 & 0x3F) << 12) | ((byte3 & 0x3F) << 6) | (byte4 & 0x3F));
                                } else {
                                    decoded = decoded + encoded.substr(i, 12);
                                    illegalencoding = illegalencoding + encoded.substr(i, 12) + " ";
                                }
                            } else {
                                decoded = decoded + encoded.substr(i, 12);
                                illegalencoding = illegalencoding + encoded.substr(i, 12) + " ";
                            }
                        } else {
                            decoded = decoded + encoded.substr(i, 12);
                            illegalencoding = illegalencoding + encoded.substr(i, 12) + " ";
                        }
                        i = i + 12;
                    }

                } else { // the first byte is not legally percent-encoded
                    decoded = decoded + encoded.substr(i, 3);
                    illegalencoding = illegalencoding + encoded.substr(i, 3) + " ";
                    i = i + 3;
                }

            } else { // the string is not percent encoded
                // Check if character is an allowed character:
                if (allowed.indexOf(ch) == -1) notallowed = notallowed + ch + " ";
                decoded = decoded + ch;
                i++;
            }
        } // end of while ...
        // Write result:
        return decoded;
    }
}




var userAgent = navigator.userAgent.toLowerCase();
var isIphone = userAgent.indexOf("iphone") > -1;
var isAndroid = userAgent.indexOf("android") > -1;

if (isIphone || isAndroid) {
	// if user uses iPhone or Android, activate logic to decide whether to redirect to App Store / Market
	var message;
    var link;
    var c_name;
    if (isIphone) {
    	message = "Did you know Haaretz is now optimized for your iPhone? The new app is the best way to get the latest news and analysis.\n\nPress OK to download Haaretz app for FREE at the App Store!";
        link = "http://itunes.apple.com/us/app/haaretz-english-edition/id475201375";
        c_name = "iPhoneRedirect";
    } else if (isAndroid) {
    	message = "Did you know Haaretz is now optimized for your Android? The new app is the best way to get the latest news and analysis from our award-winning journalists.\n\nTo experience Haaretz's breaking news, commentary and analysis, press OK to download the app for FREE at the Market!";
        link = "https://market.android.com/details?id=com.opentech.haaretz";
        c_name = "androidRedirect";
    }
     
    var defaultValue = "undefined";
    var returnValue = defaultValue;
    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;
            var values = decode(document.cookie.substring(c_start, c_end).replace(/\+/, "%20"), "utf8").split(",");
            returnValue = decode(document.cookie.substring(c_start, c_end), "utf8");
        }
    }


    if (returnValue == "undefined") // cookie does not exist
    {
        if (confirm(message)) { // ask user to confirm redirect
            // if yes - set cookie to "yes" for 90 days and redirect
            var expiredays = 90;
            var value = "yes";
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + expiredays);
            document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());

            window.location.href = link;
        } else {
            // if no - set cookie to "no" for 7 days and don't redirect - continue to site
            var expiredays = 7;
            var value = "no";
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + expiredays);
            document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
        }
    }
    // else - cookie already exists, do nothing (continue to site) 
}


