var debug = false;
var showerrors = true;
var add_token = false;
var url_www = 'http://www.cdkey.si/';
var url_http = 'http://cdkey.si/';
var tmp_string = location.href;
var GLOBAL_URL = '';
if (tmp_string.indexOf('www') !== -1) {
    GLOBAL_URL = url_www;
} else {
    GLOBAL_URL = url_http;
}
var AJAX_ERROR_1 = 'An error occurred while trying to access PHP script with AJAX request.';
var AJAX_ERROR_2 = 'Your browser does not support AJAX technology.';
var AJAX_ERROR_3 = 'You are on ' + url_www + '. Should be on ' + url_http + ' address';
var GLOBAL_INFO_1 = 'Following error occurred: ';
var translationsCupons = new Array();
var currencyRateHr = false;
translationsCupons['si'] = new Array();
translationsCupons['si'][1] = 'Vnešeni kupon žal ni veljaven!';
translationsCupons['si'][2] = "Vnešeni kupon v vrednosti ";
translationsCupons['si'][3] = " je bil odštet od skupne vrednosti naročila.";
translationsCupons['hr'] = new Array();
translationsCupons['hr'][1] = 'Kupon koji ste unjeli nažalost nije važeći!';
translationsCupons['hr'][2] = "Vrijednost unešenog kupona u iznosu od ";
translationsCupons['hr'][3] = " je bila odbijena od ukupne vrijednosti narudžbe.";
translationsCupons['en'] = new Array();
translationsCupons['en'][1] = 'Inserted coupon is invalid!';
translationsCupons['en'][2] = "Inserted coupon of value ";
translationsCupons['en'][3] = " has been deducted from the total order value.";



function redirect(link) {
    location.href = link;
}

function redirectDueToError(link, interval) {
    if (typeof (this.time) === 'undefined') {
        this.time = interval;
    }
    if (this.time === 0) {
        this.time = interval;
        location.href = link;
    } else {
        this.time = this.time - 1;
        var spantime = document.getElementById('timespan');
        spantime.innerHTML = this.time;
    }
}

function showError(message) {
    if (showerrors) {
        alert(message);
    }
}

function information(message) {
    alert(message);
}

function sendRequest(url, function_name) {
    var http_request = false;
    if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            http_request = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {
            try {
                http_request = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e) {}
        }
    }
    if (!http_request) {
        showError(AJAX_ERROR_2);
        return false;
    }
    http_request.onreadystatechange = function () {
        eval(function_name)(http_request);
    };
    url = GLOBAL_URL + url;
    if (add_token === true) {
        token = document.getElementById('token').value;
        url = url + '&token=' + token;
    }
    try {
        http_request.open('GET', url, true);
    } catch (ex) {
        showError(AJAX_ERROR_3);
    }
    http_request.send(null);
    if (debug !== false) {
        location.href = url;
    }
}

function checkHttpRequest(request) {
    switch (request.readyState) {
    case 0:
        break;
    case 1:
        break;
    case 2:
        break;
    case 3:
        break;
    case 4:
        if (request.status == 200) {
            return true;
        } else {
            return 'error';
        }
        break;
    default:
        break;
    }
    return false;
}

function getElementByID(name) {
    object = document.getElementById(name);
    if (object !== null) {
        return object;
    } else {
        return false;
    }
}

function getURLParam(strParamName) {
    var strReturn = "";
    var strHref = window.location.href;
    if (strHref.indexOf("&") > -1) {
        var strQueryString = strHref.substr(strHref.indexOf("&")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for (var iParam = 0; iParam < aQueryString.length; iParam++) {
            if (aQueryString[iParam].indexOf(strParamName + "=") > -1) {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return strReturn;
}

function isInteger(s) {
    var i;
    if (isEmpty(s)) {
        if (isInteger.arguments.length == 1) {
            return 0;
        } else {
            return (isInteger.arguments[1] === true);
        }
    }
    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (!isDigit(c)) {
            return false;
        }
    }
    return true;
}

function isEmpty(s) {
    return ((s === null) || (s.length === 0));
}

function isDigit(c) {
    return ((c >= "0") && (c <= "9"));
}
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1) return data[i].identity;
            } else if (dataProp) return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [{
        string: navigator.userAgent,
        subString: "OmniWeb",
        versionSearch: "OmniWeb/",
        identity: "OmniWeb"
    }, {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari"
    }, {
        prop: window.opera,
        identity: "Opera"
    }, {
        string: navigator.vendor,
        subString: "iCab",
        identity: "iCab"
    }, {
        string: navigator.vendor,
        subString: "KDE",
        identity: "Konqueror"
    }, {
        string: navigator.userAgent,
        subString: "Firefox",
        identity: "Firefox"
    }, {
        string: navigator.vendor,
        subString: "Camino",
        identity: "Camino"
    }, {
        string: navigator.userAgent,
        subString: "Netscape",
        identity: "Netscape"
    }, {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "Explorer",
        versionSearch: "MSIE"
    }, {
        string: navigator.userAgent,
        subString: "Gecko",
        identity: "Mozilla",
        versionSearch: "rv"
    }, {
        string: navigator.userAgent,
        subString: "Mozilla",
        identity: "Netscape",
        versionSearch: "Mozilla"
    }],
    dataOS: [{
        string: navigator.platform,
        subString: "Win",
        identity: "Windows"
    }, {
        string: navigator.platform,
        subString: "Mac",
        identity: "Mac"
    }, {
        string: navigator.platform,
        subString: "Linux",
        identity: "Linux"
    }]
};
BrowserDetect.init();

function addEvent(obj, type, fn) {
    if (obj.attachEvent) {
        obj['e' + type + fn] = fn;
        obj[type + fn] = function () {
            obj['e' + type + fn](window.event);
        };
        obj.attachEvent('on' + type, obj[type + fn]);
    } else {
        obj.addEventListener(type, fn, false);
    }
}

function removeEvent(obj, type, fn) {
    if (obj.detachEvent) {
        obj.detachEvent('on' + type, obj[type + fn]);
        obj[type + fn] = null;
    } else {
        obj.removeEventListener(type, fn, false);
    }
}

function MM_findObj(n, d) {
    var p, i, x;
    if (!d) d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n);
    return x;
}

function MM_showHideLayers() {
    var i, p, v, obj, args = MM_showHideLayers.arguments;
    for (i = 0; i < (args.length - 2); i += 3)
    if ((obj = MM_findObj(args[i])) != null) {
        v = args[i + 2];
        if (obj.style) {
            obj = obj.style;
            v = (v == 'show') ? 'visible' : (v == 'hide') ? 'hidden' : v;
        }
        obj.visibility = v;
    }
}

function MM_openBrWindow(theURL, winName, features) {
    window.open(theURL, winName, features);
}

function MM_swapImgRestore() {
    var i, x, a = document.MM_sr;
    for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

function MM_preloadImages() {
    var d = document;
    if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length,
            a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++)
        if (a[i].indexOf("#") != 0) {
            d.MM_p[j] = new Image;
            d.MM_p[j++].src = a[i];
        }
    }
}

function MM_swapImage() {
    var i, j = 0,
        x, a = MM_swapImage.arguments;
    document.MM_sr = new Array;
    for (i = 0; i < (a.length - 2); i += 3)
    if ((x = MM_findObj(a[i])) != null) {
        document.MM_sr[j++] = x;
        if (!x.oSrc) x.oSrc = x.src;
        x.src = a[i + 2];
    }
}

function getInnerWidth() {
    if (self.innerWidth) {
        frameWidth = self.innerWidth;
        frameHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientWidth) {
        frameWidth = document.documentElement.clientWidth;
        frameHeight = document.documentElement.clientHeight;
    } else if (document.body) {
        frameWidth = document.body.clientWidth;
        frameHeight = document.body.clientHeight;
    } else return;
    return frameWidth;
}

function setTargetBlank(object) {
    object.target = '_blank';
}

///////////////////////////////////
/////// CD-KEYS FUNCTIONS /////////
///////////////////////////////////
function checkSearchValue(object) {
    if (object.value == object.defaultValue) {
        object.value = '';
    } else if (object.value == '') {
        object.value = object.defaultValue;
    } else {
        object.value = object.value.replace(object.defaultValue, '');
    }
}

function checkIfShowOther() {
    if ((document.getElementById('refferer').length-1) == (document.getElementById('refferer').selectedIndex)) {
        document.getElementById('refferer_text').style.display = '';
        document.getElementById('refferer_label').style.display = '';
    } else {
        document.getElementById('refferer_text').style.display = 'none';
        document.getElementById('refferer_label').style.display = 'none';
    }
}

function calculatePrice($language){
    var currencyRate;
    switch ($language) {
        case 'hr':
            currencyRate = (currencyRateHr ? currencyRateHr : 7.4735);
            break;
        case 'si':
        default:
            currencyRate = 1;

    }

    //RM26052007 Check for price and check if games are on supplay
    var $country = getElementByID('country');
    var $country = ($country.localName == 'input'  ? $country.value : $country.options[getElementByID('country').selectedIndex].value);
    switch ($country) {
        case 'hr':
            var game_id = getElementByID('game_id').options[getElementByID('game_id').selectedIndex].value;
            var price_value = getElementByID('game_price_notax_'+game_id).value * currencyRate;
            break;
        case 'si':
        default:
            var price_value   = getElementByID('game_id').options[getElementByID('game_id').selectedIndex].title * currencyRate;
    }
    var num_cd_keys   = parseFloat(getElementByID('num_cd_keys').value);
    var c_price       = getElementByID('price');
    var c_freeshipping= getElementByID('freeshipping');
    var c_discount    = getElementByID('discount');
    var c_cuponvalue  = getElementByID('cuponvalue').value;

    if (num_cd_keys < 1) {
        num_cd_keys = 1;
    }


    price_value = price_value*num_cd_keys;


    // RM: Discount on multiple cdkeys
    price_value = price_value - ((num_cd_keys - 1) * currencyRate);

    // RM: Use Shipping / free shipping
    if (getElementByID('shipping1').checked && num_cd_keys < 3) {
        price_value = price_value + 3.00 * currencyRate;
    }

    // RM: Have cupon?
    c_cuponvalue      = parseFloat(c_cuponvalue);
    price_value       = parseFloat((price_value-c_cuponvalue));

    // RM: Moneta, 15%
    if (getElementByID('shipping4').checked) {
        price_value = price_value + ((price_value/100) * 15);
    }

    // RM: Paysafecard
    if (getElementByID('shipping5').checked) {
        price_value = price_value + ((price_value/100) * 10);
    }

    // RM: Paypal
    if (getElementByID('shipping3').checked) {
        price_value = price_value + ((price_value/100) * 3.4);
    }

    c_price.innerHTML = number_format(price_value, 2, ',', '.');
    c_discount.innerHTML = number_format((((num_cd_keys - 1) * currencyRate) + c_cuponvalue), 2, ',', '.');
}

function loginUser() {
  var emailLogin = getElementByID('email_login').value;
  var streetLogin = getElementByID('street_login').value;

  jQuery.get("index.php?m=loginUser", {email: emailLogin, street: streetLogin}, function(data){
    var loginData = JSON.parse(data);
    if (loginData && loginData.success == true) {
        jQuery('input[name="name"]').val(loginData.name);
        jQuery('input[name="lastname"]').val(loginData.lastname);
        jQuery('input[name="street"]').val(loginData.street);
        jQuery('input[name="post_code"]').val(loginData.post_code);
        jQuery('input[name="place"]').val(loginData.place);
        jQuery('input[name="email"]').val(loginData.email);

        jQuery('li.login').hide();
    }
  });
}

function checkCupon() {
    var $country = getElementByID('country');
    var $country = ($country.localName == 'input'  ? $country.value : $country.options[getElementByID('country').selectedIndex].value);

    //RM Not empty?
    if (jQuery('input[name="cupon"]').val() != '') {
        jQuery.get("index.php?m=checkcupon", {cupon: jQuery('input[name="cupon"]').val(), lang: $country}, function(data){
            var htmlCupon = translationsCupons[$country][1];

            if (data != '#error') {
              var currency = '€';
              switch ($country) {
                  case 'hr':
                      currency = 'kn';
                      break;
                  case 'si':
                  default:
                      currency = '€';
              }

              htmlCupon = translationsCupons[$country][2]+data+' '+currency+translationsCupons[$country][3];
            } else {
                data = 0.00;
            }

            jQuery('#cupondesc').removeClass('hidden');
            jQuery('#cupondesc').html(htmlCupon);
            jQuery('#cuponvalue').val(parseFloat(data));
            calculatePrice($country);

        });
    } else {
        jQuery('#cuponvalue').val(parseFloat(0.00));
        jQuery('#cupondesc').addClass('hidden');
        calculatePrice($country);
    }

    return false;
}

function calculatePriceWholesale(language){
    var sum=0;
    jQuery('.gamewholesale').each( function( intIndex ) {
        if (jQuery(this).val() != '0') {
            var tempName = jQuery(this).attr('name').replace('game_', '');
            sum = sum + parseFloat(jQuery(this).val() * parseFloat(jQuery('#price_' + tempName).get(0).innerHTML.replace('€', '')));
        }
    });

    sum = number_format(sum, 2, ',', '.');

    var currency = '€';
    switch (language) {
        case 'hr':
            currency = 'kn';
            break;
        case 'si':
        default:
            currency = '€';
    }
    jQuery('#sumGame').get(0).innerHTML = sum + currency;
}

function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec);
        return '' + Math.round(n * k) / k;
    };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function priceCalculated(http_request){
    var xmldoc = checkHttpRequest(http_request);
    if (xmldoc !== false){
        var status = http_request.responseXML.getElementsByTagName('status')[0].firstChild.data;
        if (status == 'true'){
            var on_sale = http_request.responseXML.getElementsByTagName('on_sale')[0].firstChild.data;
            var price   = http_request.responseXML.getElementsByTagName('price')[0].firstChild.data;

            getElementByID('price').value = price;
            var submit_b= getElementByID('submit_button');
            submit_b.type       = 'submit';
            submit_b.onclick    = '';
            submit_b.value      = 'Oddaj naročilo';
        }else if (status == 'false'){
            information('An error occured while trying to get price for your game. Please inform admin staff.');
        }
    }else if (xmldoc == "error"){
        showError(AJAX_ERROR_1);
    }
}

///////////////////////////////////
//////// OTHER FUNCTIONS //////////
///////////////////////////////////
function confirmChoice(href, text){
    if (window.confirm(text) === true){
        window.location = href;
        return true;
    }else{
        return false;
    }
}

function get_eur_rate(price, game_id, object, href){
    setTargetBlank(object);
    num_cd_keys         = getElementByID('num_'+game_id).value;
    price               = num_cd_keys*price;
    object.href         = href+''+price;
}

jQuery(document).ready(function(){
    //NEWS SLIDE
    if (jQuery('#news').length > 0 && jQuery('#news div').length > 1) {
        jQuery('#news').cycle({
            fx:      'scrollVert',
            timeout:  6000,
            speed:    1200,
            prev:    '#prev',
            next:    '#next',
            pause:   1
        });
    };

    jQuery('#calculate').click(function() {
        var stockPrice = parseFloat(jQuery('#stockPrice').val());
        var profit = parseFloat(jQuery('#profit').val());
        var finalPrice;
        var expense;
        var tax;

        finalPrice = stockPrice + profit;
        tax = 0.2 * finalPrice;
        finalPrice += tax;
        expense = stockPrice + tax;

        jQuery('#finalPrice').html(finalPrice);
        jQuery('#expense').html(expense);
    });

    // Get the currency if needed
    var $country = getElementByID('country');
    if ($country) {
      $country = ($country.localName == 'input'  ? $country.value : $country.options[getElementByID('country').selectedIndex].value);
    } else {
      $country = 'si';
    }

    if ($country == 'hr') {
      jQuery.get("index.php?m=currency", {'s':$country}, function(data){
        currencyRateHr = data;
      });
    }
});
