function createXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var msxmls = new Array(
                'Msxml2.XMLHTTP',
                'Microsoft.XMLHTTP');
        for (var i = 0; i < msxmls.length; i++) {
            try {
                return new ActiveXObject(msxmls[i]);
            } catch (e) {
            }
        }
    }
    throw new Error("Could not instantiate XMLHttpRequest");
}

function showMessages() {
    var url = getBase() + 'service/message.do';
    var xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                var messagesDiv = document.getElementById('messages');
                messagesDiv.style.visibility = 'visible';
                messagesDiv.style.height = 'auto';
                messagesDiv.innerHTML = xmlHttp.responseText;
                messagesDiv.style.height = 'auto';
            }
        }
    }
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

function createDRMobject() {
    var progIDs = new Array(
            "DRM.GetLicense.1",
            "DRM.GetLicense");
    for (var i = 0; i < progIDs.length; i++) {
        try {
            if ("ActiveXObject" in window) {
                return new ActiveXObject(progIDs[i]);
            } else if ("GeckoActiveXObject" in window) {
                return new GeckoActiveXObject(progIDs[i]);
            }
        } catch (e) {
        }
    }
    throw "Could not instantiate ActiveX object";
}

function storeLicenses(storer, licenses) {
    var licenseOK = (licenses.length != 0);
    for (var i = 0; i < licenses.length; i++) {
        var license = licenses[i];
        var licenseText = license.firstChild.nodeValue;
        storer.StoreLicense(licenseText);
    }
}

function showLicenseServerResult(result, messages) {
    //Clear any messages and add this whether it is error or success message
    clearWarning();
    for (var i = 0; i < messages.length; i++) {
        var message = messages[i];
        var messageText = message.firstChild.nodeValue;
        addWarning(messageText);
    }
}

function startLicenseServerWorking(messageWait) {
    incLicenseServerWorking();
    if (getErrorCounter() == 0 && getLicenseServerWorking() <= 1) {
        clearWarning();
        addWarning(messageWait);
    }
}

function endLicenseServerWorking() {
    decLicenseServerWorking();
    if (getErrorCounter() == 0 && getLicenseServerWorking() == 0) {
        clearWarning();
    }
}

function showLicenseServerResultSC(result, messages) {
    //if error exists we leave it as is, not append others
    if (getErrorCounter() > 0) {
        return;
    }
    //If this is an error then show it
    if (result != 0) {
        incErrorCounter(result);
        for (var i = 0; i < messages.length; i++) {
            var message = messages[i];
            var messageText = message.firstChild.nodeValue;
            addWarning(messageText);
        }
    }
}

function generateLicenseNew(url, imgElement, imgSuccess, imgFailed) {
    var licobj = createDRMobject();
    var xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            var resp = xmlHttp.responseText;
            if(resp.substring(0,1) == "E") {
                showWarning(resp.substring(1))
                imgElement.src = imgFailed;
                imgElement.disabled = false;
            }
            else{            
                try {
                    //store licenses
                    var xmldoc = xmlHttp.responseXML;
                    var response = xmldoc.getElementsByTagName("response").item(0);
                    var licenses = response.getElementsByTagName("licenseItem");
                    storeLicenses(licobj, licenses);
                
                    imgElement.src = imgSuccess;
                    imgElement.disabled = true;
                } catch (e) {
                    imgElement.src = imgFailed;
                    imgElement.disabled = false;
                    //alert(e.message);
                }
            }
        }
    }
    var  params = licobj.getSystemInfo();
    xmlHttp.open("POST", url, true);
    //xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    //xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(params);
}
function generateLicenseSCNew(url) {
    var licobj = createDRMobject();
    var xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            var xmldoc = xmlHttp.responseXML;
            var response = xmldoc.getElementsByTagName("response").item(0);
            try {
                //store licenses
                var licenses = response.getElementsByTagName("licenseItem");
                storeLicenses(licobj, licenses);
            } catch (e) {
            }
        }
    }
    var  params = licobj.getSystemInfo();
    xmlHttp.open("POST", url, true);
    //xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    //xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(params);
}

function generateLicenseSC(orderId, productId, messageWait) {
    //startLicenseServerWorking(messageWait);
    var url = getBase() + 'service/license/generate.do';
    var licobj = createDRMobject();
    var xmlHttp = createXMLHttpRequest();

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                var xmldoc = xmlHttp.responseXML;
                var response = xmldoc.getElementsByTagName("response").item(0);
                //store licenses
                var licenses = response.getElementsByTagName("licenseItem");
                storeLicenses(licobj, licenses);

                //endLicenseServerWorking();
            } else if (xmlHttp.status == 403) {
                /*
                 var xmldoc = xmlHttp.responseXML;
                 var response = xmldoc.getElementsByTagName("response").item(0);
                 var warnings = response.getElementsByTagName("warning");
                 showLicenseServerResultSC(1, warnings);
                 endLicenseServerWorking();
                 */
            }
        }
    }
    var params = "orderProductId=" + orderId + "&productId=" + productId + "&clientInfo=" + licobj.getSystemInfo();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(params);
}

function generateLicense_Old(orderProductId, productId, imgElement, imgProgress, imgSuccess, imgFailed) {
    var url = getBase() + 'service/license/generate.do';
    var licobj = createDRMobject();
    var xmlHttp = createXMLHttpRequest();


    xmlHttp.onreadystatechange = function() {
        var updateImage = (imgElement != undefined);

        if (xmlHttp.readyState == 1) {
            if (updateImage) {
                imgElement.src = imgProgress;
                imgElement.disabled = true;
            }
        } else if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                var xmldoc = xmlHttp.responseXML;
                var response = xmldoc.getElementsByTagName("response").item(0);

                //store licenses
                var licenses = response.getElementsByTagName("licenseItem");
                storeLicenses(licobj, licenses);
                if (updateImage) {
                    imgElement.src = imgSuccess;
                    imgElement.disabled = true;
                }
            } else {
                // In any case of response - change button back
                if (updateImage) {
                    imgElement.src = imgFailed;
                    imgElement.disabled = false;
                }
            }
        }
    }
    var params = "orderProductId=" + orderProductId + "&productId=" + productId + "&clientInfo=" + licobj.getSystemInfo();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(params);
}

function generateLicenseAll_Old(orderProductId) {
    //alert(or);
    var regexp = RegExp("lic(\\d+)?(?:_(\\d+))?");
    var images = document.getElementsByTagName("img");
    for (var i = 0; i < images.length; i++) {
        var imgElement = $(images[i]);
        var m = regexp.exec(imgElement.id)
        if (m != null) {
            var curOrderProductId = m[1];
            var trackId = m[2];
            if (trackId != undefined && curOrderProductId != undefined) {
                if (orderProductId != undefined && orderProductId != curOrderProductId) {
                    continue;
                } else if (imgElement.disabled) {
                    continue;
                }
                //imgIn.src = "images/button_License_failed.gif"
                generateLicense(curOrderProductId, trackId, imgElement, 'images/button_License_progress.gif', 'images/button_License_success.gif', 'images/button_License_failed.gif');
            }
        }
    }
}

function clearErrorCounter() {
    var errorCounter = document.getElementById("errorCounter");
    if (errorCounter != null && errorCounter != undefined) {
        errorCounter.firstChild.nodeValue = 0;
    }
}

function getErrorCounter() {
    var errorCounter = document.getElementById("errorCounter");
    if (errorCounter != null && errorCounter != undefined) {
        return Number(errorCounter.firstChild.nodeValue);
    }
    return 0;
}

function incErrorCounter(resValue) {
    var errorCounter = document.getElementById("errorCounter");
    if (errorCounter != null && errorCounter != undefined) {
        errorCounter.firstChild.nodeValue = Number(errorCounter.firstChild.nodeValue) + resValue;
    }
}

function decLicenseServerWorking() {
    var licenseServerWorking = document.getElementById("licenseServerWorking");
    if (licenseServerWorking != null && licenseServerWorking != undefined) {
        licenseServerWorking.firstChild.nodeValue = Number(licenseServerWorking.firstChild.nodeValue) - 1;
    }
}

function getLicenseServerWorking() {
    var licenseServerWorking = document.getElementById("licenseServerWorking");
    if (licenseServerWorking != null && licenseServerWorking != undefined) {
        return Number(licenseServerWorking.firstChild.nodeValue);
    }
    return 0;
}

function incLicenseServerWorking() {
    var licenseServerWorking = document.getElementById("licenseServerWorking");
    if (licenseServerWorking != null && licenseServerWorking != undefined) {
        licenseServerWorking.firstChild.nodeValue = Number(licenseServerWorking.firstChild.nodeValue) + 1;
    }
}

function serviceLoadRecommendation(templateName, userId, actionId, actionType, rule, titleName, isRotating, recomKey, forward) {
    var url = getBase() + 'service/recommendation/' + forward + '.do?';
    var xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                var divElement = document.getElementById(recomKey);
                if (xmlHttp.responseText.trim().length != 0) {
                    divElement.innerHTML = xmlHttp.responseText;
                    if (isRotating == "1") {
                        initRotating(recomKey);
                    }
                } else {
                    closeRecomDiv(recomKey);
                }
            } else {
                closeRecomDiv(recomKey);
            }
        }
    }
    var params = 'templateName=' + templateName
            + '&userId=' + userId
            + '&actionId=' + actionId
            + '&actionType=' + actionType
            + '&rule=' + rule
            + '&titleName=' + titleName
            + '&recomKey=' + recomKey;
    xmlHttp.open("GET", url + params, true);
    xmlHttp.send(null);
}

function serviceLoadRecommendationSSO(templateName, actionId, actionType, rule, titleName, recomKey, forward) {
    var url = getBase() + 'service/recommendation/' + forward + '.do?';
    var xmlHttp = createXMLHttpRequest();

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            var divElement = document.getElementById("popular-sso");
            if (xmlHttp.status == 200) {
                divElement.innerHTML = xmlHttp.responseText;
                divElement.style.display = "block";
                initRotating("popular-sso");
            } else {
                divElement.style.display = "block";
            }
        }
    }
    var params = 'templateName=' + templateName
            + '&actionId=' + actionId
            + '&actionType=' + actionType
            + '&rule=' + rule
            + '&titleName=' + titleName
            + '&recomKey=' + recomKey;
    xmlHttp.open("GET", url + params, true);
    xmlHttp.send(null);
}


function closeRecomDiv(recomKey) {
    var divElement = document.getElementById(recomKey);
    divElement.style.height = "0px";
    divElement.style.lineHeight = "0px";
    divElement.style.clear = "both";
}
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}

String.prototype.ltrim = function() {
    return this.replace(/^\s+/, "");
}

String.prototype.rtrim = function() {
    return this.replace(/\s+$/, "");
}


function cacheImages() {
    var img_names = new Array(
            "./images/b_buy_adding.gif",
            "./images/b_buy_added.gif"
            );
    var imgs = new Image();
    for (var i = 0; i < img_names.length; i++) {
        imgs.src = img_names[i];
    }
    imgs = null;
}

//function wishlistAdd(productId,title,artistname,ptid, imgTagElement, isRecom, imgSrcNormal, imgSrcProcess, imgSrcDone) {
//    var url = getBaseReal() + 'Handlers/wishlistadd.ashx?';

//    var params = "productId=" + productId + "&title=" + encodeURI(title) + "&artistname=" + encodeURI(artistname) + "&ptid=" +ptid;
//    if (isRecom) {
//        params += "&recommendation=true";
//    }

//    var xmlHttp = createXMLHttpRequest();

//    xmlHttp.onreadystatechange = function() {
//        if (xmlHttp.readyState == 2) {
//            imgTagElement.src = imgSrcProcess;
//        } else if (xmlHttp.readyState == 4) {
//            if (xmlHttp.status == 401) {
//                var referral = location.href.replace(getBaseReal(), '/');
//                location.href = getBase() + 'wishlistadd.aspx?' + params + '&referral=' + encodeURI(referral);
//            } else if (xmlHttp.status == 200) {
//                imgTagElement.src = imgSrcDone;
//                if(xmlHttp.responseText == '1')
//                    window.location.href= getBaseReal() + 'web/login.aspx';
//                else
//                   displayMessages(xmlHttp.responseText);
//            } else {
//                imgTagElement.src = imgSrcNormal;
//                displayWarnings(xmlHttp.responseText);
//            }
//        }
//    }
//    xmlHttp.open("GET", url + params, true);
//    xmlHttp.send(null);
//}
function serviceLoadProductRateOrder(productId, divId) 
{    
    //var url = getBase() + '/service/rating/orderproductrate/load.do';
    //url = url + '?productId=' + productId;
    var url = getBaseReal() + '/handlers/UserProductRating.ashx';
    url = url + '?productId=' + productId+"&divid="+divId;
    serviceProductRateOrder(url, divId, productId);
}
function serviceSaveProductRateOrder(productId, rate, divId) {
    if (rate == 0) return;
    //var url = getBase() + '/service/rating/orderproductrate/save.do';
    //url = url + '?productId=' + productId + '&rate=' + rate;        
    var url = getBaseReal() + '/handlers/UserProductRating.ashx';
    url = url + '?productId=' + productId + '&rate=' + rate+"&divid="+divId;
    serviceProductRateOrder(url, divId, productId);
}

function serviceProductRateOrder(url, divId, productId) {

    var xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                var divElement = document.getElementById(divId);
                divElement.innerHTML = xmlHttp.responseText;
                init_rating_order(divId, productId);                
            }
        }
    };
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}
//Add a product to Shopping Cart
function shoppingCartAdd(productId,type,title,artist,imgTagElement, isRecom, imgSrcNormal, imgSrcProcess, imgSrcDone) {
    try{
        var url = getBaseReal() + 'Handlers/ShoppingCart.ashx?action=add';
        var xmlHttp = createXMLHttpRequest();
        xmlHttp.onreadystatechange = function() {        
            if (xmlHttp.readyState == 2) {
                imgTagElement.src = imgSrcProcess;
            } else if (xmlHttp.readyState == 4) {
                if (xmlHttp.status == 200) {
                    imgTagElement.src = imgSrcDone;
                    var strResponse = xmlHttp.responseText;
                    String.prototype.startsWith = function(strResponse) 
                    {return (this.match("^"+strResponse)==strResponse)}                       
                    if(strResponse.startsWith('error'))
                        displayWarnings(strResponse.substring(6));
                    else
                        displayMessages(xmlHttp.responseText);
                    updateShoppingCartCount();
                    //updateShoppingCartView();
                } else {
                    imgTagElement.src = imgSrcNormal;
                    displayWarnings(xmlHttp.responseText);
                }
            }
        }
        url += '&productId=' + productId + '&type='+type + '&title='+encodeURI(title) + '&artist=' +encodeURI(artist) + '&isRecom=' +isRecom;   
        xmlHttp.open("GET", url, true); 
        xmlHttp.send(null);
    }
    catch(e){
       var exec = e;
    }
}
//Update Shopping Cart Product count
function updateShoppingCartCount() {
    var url = getBaseReal() + 'Handlers/ShoppingCart.ashx?action=count';
    var xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                var count = xmlHttp.responseText;
                var divElement2 = document.getElementById('shoppingcart_product_count');
                if(divElement2 != null)
                    divElement2.innerHTML = count.trim();
                //updateShoppingCartView();
            }
        }
    }
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

//ShoppinpCart Products View
function updateShoppingCartView() {
    var sc = $('sc_wrapper');
    if (sc.style.display == "block") {
        var url = getBaseReal() + 'Handlers/ShoppingCart.ashx?action=view';
        var xmlHttp = createXMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4) {
                if (xmlHttp.status == 200) {
                    var divActive = document.getElementById('sc_wrapper');
                    if(divActive != null)
                        divActive.innerHTML = xmlHttp.responseText;
                }
            }
        }
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
}
//Remove product from shopping cart
function shoppingCartProductRemove(productId) {
    var url = getBaseReal() + 'Handlers/ShoppingCart.ashx?action=remove';
    var xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                updateShoppingCartCount();
                updateShoppingCartView();
            }
        }
    }
    url += '&productId=' + productId;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

//Shopping cart initialization
function shoppingCartUpdateAndInit() {
    updateShoppingCartCount();
    //updateShoppingCartView();
    sc_preview_init();
}

/* OrderProduct's tags begin*/
function orderProductTagSave(orderProductId, tags) {
    var url = getBaseReal() + 'orderproduct/tagssave.ashx';
    var xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                window.location.reload();
            }
        }
    }
    url += '?orderProductId=' + orderProductId;
    url += '&tags=' + encodeURIComponent(tags);
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}


function orderProductTagEdit(obj, orderProductId) {
    var url = getBaseReal() + 'orderproduct/TagsEdit.ashx';
    var xmlHttp = createXMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                var sMsg =  xmlHttp.responseText;
                popup_tags_edit(obj, sMsg);
                 
            }
        }
    }
    url += '?orderProductId=' + orderProductId;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}
function popup_tags_edit_Old(obj, orderProductId, text) {
    var objPos = $(obj).getCoordinates();

    var popup_tags_edit = $('popup_tags_edit');
    if (!popup_tags_edit) {
        popup_tags_edit = new Element("div");
        popup_tags_edit.setAttribute("id", "popup_tags_edit");
       popup_tags_edit.className = "n_search_sc"; 
        popup_tags_edit.injectInside($E('body'));
    }
    popup_tags_edit.innerHTML = text;
    popup_tags_edit.setStyle('position', 'absolute');
    popup_tags_edit.setStyle('top', objPos.top);
    popup_tags_edit.setStyle('left', objPos.left + objPos.width + 10);
    popup_tags_edit.setStyle('display', 'block');
   // alert(  popup_tags_edit.style.display);
    
    var popup_tags_text = $('popup_tag_text');
    popup_tags_text.focus();

    $('popup_tag_save').onclick = function() {
        orderProductTagSave(orderProductId, popup_tags_text.value)
    };
    $('popup_tag_cancel').onclick = function() {
        popup_tags_edit.setStyle('display', 'none');
    };
    $('popup_close').onclick = function() {
        popup_tags_edit.setStyle('display', 'none');
    };
}
/* OrderProduct's tags end*/


function updateAllRating(productId) {    
    //product_rating_1501305_12472262
    //var regexp = RegExp("lic(\\d+)?(?:_(\\d+))?");
    var regexp = RegExp("product_rating_"+productId+"_\\d");
    var divs = document.getElementsByTagName("div");
    for (var i = 0; i < divs.length; i++) {
        var divElement = $(divs[i]);
        var m = regexp.exec(divElement.id)
        if (m != null) {
                serviceLoadProductRateOrder(productId,divElement.id);
            }
        }
}

function popup_tags_edit(obj, orderProductId, text) {
}

function getposOffset(overlay, offsettype){
var totaloffset=(offsettype=="left")? overlay.offsetLeft : overlay.offsetTop;
var parentEl=overlay.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function popup_tags_edit(curobj,text)
{
       var subobjstr='popup_tags_edit'; 
       var opt_position='leftbottom';
       if (document.getElementById(subobjstr) != null)
       {
           var subobj=document.getElementById(subobjstr);
           subobj.innerHTML = text;
         //  alert(subobj.style.display);
          // subobj.style.display=(subobj.style.display!="block")? "block" : "none";
           //      (subobj.style.display!="block")? "block" : "none";
           var xpos=getposOffset(curobj, "left")+((typeof opt_position!="undefined" && opt_position.indexOf("right")!=-1)? -(subobj.offsetWidth-curobj.offsetWidth) : 0) ;
           var ypos=getposOffset(curobj, "top")+((typeof opt_position!="undefined" && opt_position.indexOf("bottom")!=-1)? curobj.offsetHeight : 0);
           
           subobj.style.left=xpos+"px";
           subobj.style.top=ypos+"px";
           subobj.style.display= "block";
           return false
       }
       else
          return true
}

function closeTagsDiv() {
document.getElementById('popup_tags_edit').style.display="none";
}

function isNumberKey(evt)
{
    var charCode=(evt.which)? evt.which : event.keyCode
    if(charCode<48 || charCode>57)
        return false;
    return true;
}


