var loc = location.href;

function redirect(url) { window.location = url; }

/*
 * FUNCTIONS FOR SIGNUP
 */
function enableScr(scrObjName, show)
{
    if (scrObjName == 'dlgLogin') {
        if (show) {
            dlgLogin.show();
        } else {
            dlgLogin.hide();
        }
    } else if (scrObjName == 'dlgRegister') {
        var callback = {
            success: function(o) {
                if (o.status == 200) {
                    dlgRegister.setBody(o.responseText);
                } else {
                    dlgRegister.setBody("<div align='center' style='color:#ff0000;'>LOADING FAILED: There was a problem with the request</div>");
                }
            },
            failure: function(o) {
                dlgRegister.setBody("<div align='center' style='color:#ff0000;'>LOADING FAILED: There was a problem with the request</div>");
            }
        };

        dlgRegister.setBody("<div align='center' style='margin-top:5px;color:#008800;font-size:16px;'>Loading...</div>");

        var httpRequest = YAHOO.util.Connect.asyncRequest('GET', 'http://www.warez.com/srv/signup.php?mode=register', callback);

        if (show) {
            dlgRegister.show();
        } else {
            dlgRegister.hide();
        }
    }
}

function login(url)
{
    var form     = document.loginForm;
    var login    = form.elements['username'].value;
    var password = form.elements['password'].value;

    if (login && password) {
        var callback = {
            success: function(o) {
                if (o.status == 200) {
                    if (o.responseText.indexOf('logginFailed') != -1) {
                        showNotify("Error", "Incorrect login or password.");
                    } else {
                        enableScr('dlgLogin', false);
                    }
                } else {
                    showNotify("Error", "LOADING FAILED: There was a problem with the request.");
                }
            },
            failure: function(o) {
                showNotify("Error", "LOADING FAILED: There was a problem with the request.");
            }
        };

        YAHOO.util.Connect.setForm(form);

        var httpRequest = YAHOO.util.Connect.asyncRequest('POST', url, callback);
    } else {
        showNotify("Warning", "Please fill login and password fields.");
    }
}

function register(url)
{
    var form = document.registerForm;
    var msg  = "";
    var el, subEl;

    var callback = {
        success: function(o) {
            if (o.status == 200) {
                if (o.responseText.indexOf('ok') != -1) {
                    showNotify("Message", "Welcome to My Warez!<br />Your Account has been created.<br />You will be redirected to the Wizard page in 3 sec.");

                    setTimeout("redirect('http://my.warez.com/wizard.php')", 3000);
                } else if (o.responseText.indexOf('dbduplicate') != -1) {
                    showNotify("Error", "Login or email you submitted already taken. Please, try another.");
                } else if (o.responseText.indexOf('validate') != -1) {
                    var str = o.responseText;

                    str = str.replace("validate\n", "");
                    str = "<p style='margin:0px;padding:0px;margin-top:5px;'>- " + str;
                    str = str.replace(/\n$/, "</p>");
                    str = str.replace(/\n/g, "</p><p style='margin:0px;padding:0px;margin-top:5px;'>- ");

                    showNotify("Error", "<b>Please, fill out the form correctly</b><br />" + str);
                } else {
                    showNotify("Error", "We've experienced some problems on server. Please try again later.\n");
                }

                var picPath = o.getResponseHeader['Captcha'];
                var captcha = document.getElementById('captcha');

                if (picPath != '' && picPath != null && captcha) {
                    captcha.src = 'http://www.warez.com/protected/' + picPath;
                }
            } else {
                showNotify("Error", "LOADING FAILED: There was a problem with the request.");
            }
        },
        failure: function(o) {
            showNotify("Error", "LOADING FAILED: There was a problem with the request.");
        }
    };

    YAHOO.util.Connect.setForm(form);

    var httpRequest = YAHOO.util.Connect.asyncRequest('POST', url, callback);
}

function showNotify(headerText, bodyText)
{
    mask = document.getElementById('notify_mask');

    if (mask) {
        mask.style.zIndex = 25000;
    }

    notify.setHeader(headerText);
    notify.setBody(bodyText);
    notify.render();
    notify.show();
}

function checkLogin(url, notifyEnable)
{
    if (!notifyEnable) {
        var notify = document.getElementById("notify");
    }

    var login  = document.registerForm.elements["user[login]"].value;
    var email  = document.registerForm.elements["user[email]"].value;
    errColor   = "#c20000";
    sucColor   = "green";

    if (!notifyEnable) {
        document.getElementById("tnotify").style.display = "block";
    }

    var callback = {
        success: function(o) {
            if (o.status == 200) {
                var response = o.responseText;

                if (response.indexOf("loginExist") != -1) {
                    if (!notifyEnable) {
                        notify.innerHTML = "Login or e-mail already exist";
                        notify.style.color = errColor;
                    } else {
                        showNotify("Error", "<p style='color:" + errColor + ";'>Login or e-mail already exist</p>");
                    }
                } else if (response.indexOf("loginFExist") != -1) {
                    if (!notifyEnable) {
                        notify.innerHTML = "Login or e-mail already registered for forum user. If you click 'Register' you'll be registered only as Warez.com user.";
                        notify.style.color = errColor;
                    } else {
                        showNotify("Warning", "<p style='color:" + errColor + ";'>Login or e-mail already registered for forum user. If you click 'Register' you'll be registered only as Warez.com user.</p>");
                    }
                } else if (response.indexOf("incorrectLogin") != -1) {
                    if (!notifyEnable) {
                        notify.innerHTML = "Login is incorrect.";
                        notify.style.color = errColor;
                    } else {
                        showNotify("Error", "<p style='color:" + errColor + ";'>Login is incorrect.</p>");
                    }
                } else if (response.indexOf("incorrectEmail") != -1) {
                    if (!notifyEnable) {
                        notify.innerHTML = "E-mail is incorrect.";
                        notify.style.color = errColor;
                    } else {
                        showNotify("Error", "<p style='color:" + errColor + ";'>E-mail is incorrect.</p>");
                    }
                } else {
                    if (!notifyEnable) {
                        notify.innerHTML = "Login is available.";
                        notify.style.color = sucColor;
                    } else {
                        showNotify("Message", "<p style='color:" + sucColor + ";'>Login is available.</p>");
                    }
                }
            } else {
                if (!notifyEnable) {
                    notify.innerHTML = "LOADING FAILED: There was a problem with the request";
                } else {
                    showNotify("Error", "<p style='color:" + errColor + ";'>LOADING FAILED: There was a problem with the request.</p>");
                }
            }
        },
        failure: function(o) {
            if (!notifyEnable) {
                notify.innerHTML = "LOADING FAILED: There was a problem with the request";
            } else {
                showNotify("Error", "<p style='color:" + errColor + ";'>LOADING FAILED: There was a problem with the request.</p>");
            }
        }
    };

    if (login && email) {
        if (!notifyEnable) {
            notify.innerHTML   = "Please wait...";
            notify.style.color = sucColor;
        }

        r = YAHOO.util.Connect.asyncRequest('GET', url + '?check&l=' + login + '&m=' + email, callback);
    } else {
        if (!notifyEnable) {
            notify.innerHTML = "Please fill out both 'User Name' and 'E-mail' fields.";
            notify.style.color = errColor;
        } else {
            showNotify("Error", "<p style='color:" + errColor + ";'>Please fill out both 'User Name' and 'E-mail' fields.</p>");
        }
    }
}

/**
 * function converts xml text to xml document
 *
 * @param str xml text
 *
 * @return xml document object
 */
function text2xml(str) {var xml; if (document.implementation && document.implementation.createDocument) {/* Netscape, Mozilla */ var xml = document.implementation.createDocument("", "", null); var objDOMParser = new DOMParser(); xml = objDOMParser.parseFromString(str, 'text/xml');} else if (document.all) {/* Internet Explorer */ var xml = new ActiveXObject("Microsoft.XMLDOM"); xml.loadXML(str);} return xml;}

/*
 * FUNCTIONS FOR DOWNLOADS NAVIGATION
 */
function setActiveSubcat(active) {document.getElementById("subcat_" + active).className = "aSubcat";}

function setActiveCtlgH(color, ctlgName) {var imageName = 'topm_' + ctlgName; clearCtlgH(color); document.images[imageName].src = 'http://i.warez.com/' + color + '/tabm_' + ctlgName + '_a.gif'; document.getElementById('ctlg_' + ctlgName).style.display = 'block';}

function clearCtlgH(color) {var imgName; var ctlgName; for (i = 0; i < topsImg.length; i++) {imgName = topsImg[i]; ctlgName = topsCtlg[i]; document.images[imgName].src = 'http://i.warez.com/' + color + '/tabm_' + ctlgName + '_i.gif'; document.getElementById('ctlg_' + ctlgName).style.display = 'none';}}

/*
 * FUNCTIONS FOR BB CODE PARSE AND INSERT
 */
function addQuote(id, publisher) {var str = document.getElementById('desc_' + id).innerHTML; str = str.replace(/<!--QUOTE_START-->/g, '[QUOTE]'); str = str.replace(/<!--QUOTE_END-->/g, '[/QUOTE]'); str = str.replace(/<!--BOLD_START-->/g, '[BOLD]'); str = str.replace(/<!--BOLD_END-->/g, '[/BOLD]'); str = str.replace(/<[^<>]+>/g, ''); var val = '[QUOTE][BOLD]' + publisher + ' wrote:[/BOLD] ' + str + '[/QUOTE]'; var field = document.submitItem.elements['input[description]']; insertIntoText(field, val);}

/**
 * function inserts string into text
 *
 * @param object field form field object reference
 * @param string val inserting string value
 */
function insertIntoText(field, val) {if (document.selection) {/* IE support */ field.focus(); sel = document.selection.createRange(); sel.text = val;} else if (field.selectionStart || field.selectionStart == '0') {/* MOZILLA/NETSCAPE support */ var startPos = field.selectionStart; var endPos = field.selectionEnd; field.value = field.value.substring(0, startPos) + val + field.value.substring(endPos, field.value.length); field.selectionStart = startPos + val.length; field.selectionEnd = startPos + val.length; field.focus();} else {field.value += val;}}

/*
 * OTHER FUNCTIONS
 */
function checkLen(sourceElem, resElem, maxLen) {if (document.all) {resElem.value = sourceElem.value.length;} else {resElem.value = sourceElem.textLength;} if (resElem.value >= maxLen) {sourceElem.value = sourceElem.value.substring(0, maxLen); resElem.value = sourceElem.value.length;}}

function setDefaultGenre() {for (var i = 1; i < parentCat.length; i++) {if (parentCat[i][0] == document.getElementById("parentId").value) {document.getElementById("catId").value = parentCat[i][1];}}}

function correctPrices(elem, name) {elem = document.submitItem.elements[elem]; var off = document.submitItem.elements[name].checked; elem.disabled = off; if (!off && !elem.value) {elem.value = "0.99";} if (off) {elem.value = "";}}

/*function validateTrack(idx) {for (var i = 1; i< bitrate.length; i++) {correctPrices('input[price' + bitrate[i] + ']', 'price' + bitrate[i]);} if (idx) {var prevCheck = false; for (var i = idx; i > = 1; i--) {if (prevCheck) {document.submitItem.elements['price' + bitrate[i]].checked = true;} correctPrices('input[price' + bitrate[i] + ']', 'price' + bitrate[i]); prevCheck = document.submitItem.elements['price' + bitrate[i]].checked} prevCheck = true; for (var i = idx; i < bitrate.length; i++) {if (!prevCheck) {document.submitItem.elements['price' + bitrate[i]].checked = false;} correctPrices('input[price' + bitrate[i] + ']', 'price' + bitrate[i]); prevCheck = document.submitItem.elements['price' + bitrate[i]].checked}} var elem; var isError = false; var errMsg = ''; var currPrice = ''; var prevPrice = ''; for (var i = 1; i < bitrate.length; i++) {elem = document.submitItem.elements['input[price' + bitrate[i] + ']']; if (elem.value) {currPrice = elem.value; if (currPrice <= prevPrice) {isError = true; errMsg = "'Price for " + bitrate[i] + " kbps' must be greater than previous"; break;} prevPrice = elem.value;}} currPrice = ''; prevPrice = 'null'; issetPrice = false; for (var i = bitrate.length - 1; i > = 1; i--) {elem = document.submitItem.elements['input[price' + bitrate[i] + ']']; currPrice = elem.value; if (issetPrice && prevPrice == '' && currPrice) {isError = true; errMsg = "Track with " + bitrate[i] + " kbps bitrate must be free"; break;} if (elem.value) {issetPrice = true;} prevPrice = elem.value;} if (isError) {document.getElementById("error_msg").innerHTML = errMsg; document.getElementById("error_msg").style.display = "block"; document.getElementById("submit_div").style.display = "none"; return false;} else {document.getElementById("error_msg").style.display = "none"; document.getElementById("submit_div").style.display = "block"; return true;}}*/

/**
 * Convert location.search into an array of values
 * indexed by name.
 *
 * @return array of parameters
 */
function getSearchAsArray() {var minNav3 = (navigator.appName == 'Netscape' && parseInt(navigator.appVersion) >= 3); var minIE4 = (navigator.appName.indexOf('Microsoft') >= 0 && parseInt(navigator.appVersion) >= 4); var minDOM = minNav3 || minIE4; /* baseline DOM required for this function */ var results = new Array(); if (minDOM) {var input = unescape(location.search.substr(1)); if (input) {var srchArray = input.split('&'); var tempArray = new Array(); for (var i = 0; i < srchArray.length; i++) {tempArray = srchArray[i].split('='); results[tempArray[0]] = tempArray[1];}}} return results;}

function checkSize(val) {el = document.getElementById('size'); if (val == 1) {el.style.display = 'none';} else {el.style.display = 'inline';}}

/**
 * function for retrieve cookie
 */
function getCookie(name) {var value = ''; var posName = document.cookie.indexOf(escape(name) + '='); if (posName != -1) {var posValue = posName + (escape(name) + '=').length; var endPos = document.cookie.indexOf(';', posValue); if (endPos != -1) {value = unescape(document.cookie.substring(posValue, endPos));} else {value = unescape(document.cookie.substring(posValue));}} return value;}

/**
 * function for setup cookie value
 */
function setCookie(name, value, expires, path, domain, secure) {document.cookie = name + "=" + escape (value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");}

/**
 * Keeps the javascript document.domain in its most generalized form.
 * "www.warez.com" becomes "warez.com"
 *
 * @return none
 */
function generalizeDomain() {var domainArray = document.domain.split("."); var domainArrayLength = domainArray.length; if (domainArrayLength >= 2) document.domain = domainArray[domainArrayLength - 2] + "." + domainArray[domainArrayLength - 1]; }

function checkCountryState(countryEl, stateEl)
{
    if (countryEl.options[countryEl.selectedIndex].text == 'United States of America') {
//        stateEl.disabled = false;
        stateEl.style.display = 'block';
    } else {
        stateEl.selectedIndex = 0;
	stateEl.style.display = 'none';
//        stateEl.disabled = true;
    }
}