/** Popup to show RFI request */
function showRFIPopUp(siteHome) {
    var selected = getCheckedByName('rfi-item');
    if (selected.length == 0) {
        selected = getByName('rfi-main-item');
    }
    if (selected.length != 0) {
        //log rfi call
        for (var idx = 0; idx < selected.length; ++idx) {
            logClickthrough(null, "rfi:" + selected[idx]);
        }

        //open rfi popup
        var rfiObjects = document.getElementById('rfiObjects');
        rfiObjects.value = getCommaSeparatedList(selected);
        url = '/proIdea-public/rfi-' + siteHome + '.do';
        var rfiWindow = window.open(url, 'rfiWindow', 'top=100,left=300,width=680,height=464,toolbar=no,menubar=no,scrollbars=no,resizable=yes,location=no,status=no');
        //rfiWindow.resizeTo(680, 464);
        //rfiWindow.moveTo(300, 100);
		rfiWindow.focus();
    } else {
        alert('Az Információkérés használatához pipálja ki az Önt érdeklő termék előtt található jelölőnégyzetet.');
    }
}

/** Returns the array as comma separated list. */
function getCommaSeparatedList(anArray) {
    var result = "";
    for (var idx = 0; idx < anArray.length; ++idx) {
        result += anArray[idx] + ",";
    }
    return result;
}

/** Popup to show email request */
function sendEmail(statId, name, domain, siteHome) {
    logClickthrough(statId, name + "@" + domain);

    var rfiObjects = document.getElementById('rfiObjects');
    rfiObjects.value = getListByName('rfi-main-item');
    if (rfiObjects.value != '') {
        var rfiEmail = document.getElementById('rfiEmail');
        rfiEmail.value = name + "@" + domain;

        url = '/proIdea-public/rfi-' + siteHome + '.do?sendEmail=1';
        var rfiWindow = window.open(url, 'rfiWindow', 'top=100,left=300,width=680,height=464,toolbar=no,menubar=no,scrollbars=no,resizable=yes,location=no,status=no');
        //rfiWindow.resizeTo(680, 464);
        //rfiWindow.moveTo(300, 100);
		rfiWindow.focus();
    } else {
        alert('Az Információkérés használatához pipálja ki az Önt érdeklő termék előtt található jelölőnégyzetet.');
    }
}

function compareProducts() {
    var productIds = document.getElementById('productIds');
    var value = getCheckedListByName('rfi-item');
     if (value != '' && value.lastIndexOf(',') == value.length - 1) {
        value = value.substring(0, value.length - 1);
    }
    productIds.value = value;
    if (productIds.value != '') {
        var form = document.getElementById("compareProductsForm");
        form.submit();
    } else {
        alert('Az Összehasonlítás használatához pipálja ki az Önt érdeklő termék előtt található jelölőnégyzetet.');
    }
}

/**
 * Checks if the currently loaded page is cached (not loaded from a named host)
 */
function isCachedPage() {
    theRegexp = /\d{2,3}\.\d{2,3}\.\d{2,3}\.\d{2,3}/;
    return theRegexp.test(window.location.hostname);
}

/**
 * The client data logger script to be included into each page.
 */
function clientDataCollector() {
    if (isCachedPage()) return;

    var stringArray = new Array();
    stringArray[0] = 'window.history[0]=' + window.history[0];
    if (window.opener != null && window.opener.location != null) {
        stringArray[1] = 'window.opener.location.hostname=' + window.opener.location.hostname;
        stringArray[2] = 'window.opener.location.pathname=' + window.opener.location.pathname;
        stringArray[3] = 'window.opener.location.port=' + window.opener.location.port;
        stringArray[4] = 'window.opener.location.protocol=' + window.opener.location.protocol;
        stringArray[5] = 'window.opener.location.search=' + window.opener.location.search;
    }
    else {
        stringArray[1] = 'window.opener.location.hostname=null';
        stringArray[2] = 'window.opener.location.pathname=null';
        stringArray[3] = 'window.opener.location.port=null';
        stringArray[4] = 'window.opener.location.protocol=null';
        stringArray[5] = 'window.opener.location.search=null';
    }

    stringArray[6] = 'navigator.appCodeName=' + navigator.appCodeName;
    stringArray[7] = 'navigator.appMinorVersion=' + navigator.appMinorVersion;
    stringArray[8] = 'navigator.appName=' + navigator.appName;
    stringArray[9] = 'navigator.appVersion=' + navigator.appVersion;
    stringArray[10] = 'navigator.browserLanguage=' + navigator.browserLanguage;
    stringArray[11] = 'navigator.cookieEnabled=' + navigator.cookieEnabled;
    stringArray[12] = 'navigator.cpuClass=' + navigator.cpuClass;
    stringArray[13] = 'navigator.platform=' + navigator.platform;
    stringArray[14] = 'navigator.systemLanguage=' + navigator.systemLanguage;
    stringArray[15] = 'navigator.userAgent=' + navigator.userAgent;
    stringArray[16] = 'navigator.userLanguage=' + navigator.userLanguage;

    stringArray[17] = 'screen.availHeight=' + screen.availHeight;
    stringArray[18] = 'screen.availWidth=' + screen.availWidth;
    stringArray[19] = 'screen.colorDepth=' + screen.colorDepth;
    stringArray[20] = 'screen.fontSmoothingEnabled=' + screen.fontSmoothingEnabled;
    stringArray[21] = 'screen.updateInterval=' + screen.updateInterval;

    RequestLogUtilDWR.logClientData(stringArray);
}

/**
 * The page request logger script to be included into each page.
 */
function requestLogCollector(needFeedback) {
    if (isCachedPage()) return;

    var products = getValuesByName("requestLogCollectorResourceId");
    var stringArray = new Array();
    stringArray[0] = 'window.location.href=' + window.location.href;
    if (window.opener != null && window.opener.location != null) {
        var hostname = window.opener.location.hostname;
        stringArray[1] = 'window.opener.location.hostname=' + hostname;
    } else {
        stringArray[1] = 'window.opener.location.hostname=null';
    }
    //try to get visit cookie
    var cookieValue = readCookie('client.visit.uniquekey');
    if (!cookieValue) {
        //cookie not found -> create
        cookieValue = generateTimestamp();
        createCookie('client.visit.uniquekey', cookieValue, 30);
    }
    stringArray[2] = 'client.visit.uniquekey=' + cookieValue;
    //try to get visitor cookie
    cookieValue = readCookie('client.visitor.uniquekey');
    if (!cookieValue) {
        //cookie not found -> create
        cookieValue = generateTimestamp();
        createCookie('client.visitor.uniquekey', cookieValue, 525600); //365 * 24 * 60
    }
    stringArray[3] = 'client.visitor.uniquekey=' + cookieValue;
    if (document.referrer != null) {
        stringArray[4] = 'document.referrer=' + document.referrer;
    } else {
        stringArray[4] = 'document.referrer=null';
    }
    if (needFeedback) {
        RequestLogUtilDWR.logRequest(products, stringArray, requestLogCollectorCallback);
    } else {
        RequestLogUtilDWR.logRequest(products, stringArray, requestLogCollectorDummyCallback);
    }
}

/**
 * The page request logger script to be included for download links.
 */
function logDownload(prId, docUrl) {
    if (isCachedPage()) return;

    var products = new Array();
    products[0] = prId;
    var stringArray = new Array();
    stringArray[0] = 'window.location.href=http://' + document.domain + docUrl;
    if (window.opener != null && window.opener.location != null) {
        stringArray[1] = 'window.opener.location.hostname=' + window.opener.location.hostname;
    } else {
        stringArray[1] = 'window.opener.location.hostname=null';
    }
    RequestLogUtilDWR.logRequest(products, stringArray, requestLogCollectorDummyCallback);
}

/**
 * The page request logger script to be included for download links.
 */
function logClickthrough(pupaId, address) {
    if (isCachedPage()) return;

    var stringArray = new Array();
    if (pupaId) {
        stringArray[0] = 'pupaId=' + pupaId;
    } else {
        stringArray[0] = 'pupaId=';
    }
    stringArray[1] = 'address=' + address;
    RequestLogUtilDWR.logClickthrough(stringArray);
}

/**
 * Given a string that is the name of the elements, create an string array from the
 * elements' id attribute.
 */
function getValuesByName(tagname) {
    var reply = new Array();
    var nodes = document.getElementsByName(tagname);
    for (var i = 0; i < nodes.length; i++) {
        reply[i] = nodes[i].id;
    }
    return reply;
}

/**
 * Given a string that is the name of the elements, create a comma separated list from the
 * elements' id attribute. Only checked checkboxes will be collected.
 */
function getCheckedListByName(tagname) {
    var reply = '';
    var nodes = document.getElementsByName(tagname);
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].type == 'checkbox' && nodes[i].checked && nodes[i].id != null && nodes[i].id != '') {
            reply = reply + nodes[i].id + ',';
        }
    }
    return reply;
}

/**
 * Given a string that is the name of the elements, create an array from the
 * elements' id attribute. Only checked checkboxes will be collected.
 */
function getCheckedByName(tagname) {
    var reply = new Array();
    var nodes = document.getElementsByName(tagname);
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].type == 'checkbox' && nodes[i].checked && nodes[i].id != null && nodes[i].id != '') {
            reply[i] = nodes[i].id;
        }
    }
    return reply;
}

/**
 * Given a string that is the name of the elements, create a comma separated list from the
 * elements' id attribute. All element with the specified name will be collected.
 */
function getListByName(tagname) {
    var reply = '';
    var nodes = document.getElementsByName(tagname);
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].id != null && nodes[i].id != '') {
            reply = reply + nodes[i].id + ',';
        }
    }
    return reply;
}

/**
 * Given a string that is the name of the elements, create an array from the
 * elements' id attribute. All element with the specified name will be collected.
 */
function getByName(tagname) {
    var reply = new Array();
    var nodes = document.getElementsByName(tagname);
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].id != null && nodes[i].id != '') {
            reply[i] = nodes[i].id;
        }
    }
    return reply;
}

function requestLogCollectorCallback(data) {
    dwr.util.setValue("requestLogCollectorResult", data);
}

function requestLogCollectorDummyCallback(data) {
}

/**
 * checks if the required field has been left empty -> form not allowed to submit
 */
function validateField(thisValue) {
    var valueToCheck = document.getElementById(thisValue);
    if (valueToCheck.value == null || valueToCheck.value == "") {
        valueToCheck.focus();
        return false;
    }
}

/*
 * Creates a new cookie.
 */
function createCookie(name, value, mins) {
    var expires = "";
	if (mins) {
		var date = new Date();
		date.setTime(date.getTime() + (mins * 60000));
		var expires = "; expires=" + date.toGMTString();
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}


/*
 * Reads cookie by the given name.
 */
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

/*
 * Deletes cookie by the given name.
 */
function deleteCookie(name) {
	createCookieT(name, "", -1);
}

/*
 *
 */
function generateTimestamp() {
    return new Date().getTime();
}

/* Show Printable version in popup window*/
function showPrintableVersion() {
    var disp_setting = "toolbar=yes,location=no,directories=yes,menubar=yes,";
    disp_setting += "scrollbars=yes,width=1024, height=700, left=40, top=40";

    if (document.getElementById("contentSubPages") != null) {
        var content = document.getElementById("contentSubPages").innerHTML;
    } else {
        var content = document.getElementById("content").innerHTML;
    }
    var printedHeader = document.getElementById("printHeader").innerHTML;

    var docprint = window.open("", "", disp_setting);
    docprint.document.open();
    docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//Dtd XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/Dtd/xhtml1-transitional.dtd">');
    docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">');
    docprint.document.write('<html><head><title>' + document.title + '</title><link href="/css/proidea_public.css" rel="stylesheet" type="text/css">');
    docprint.document.write('</head><body onLoad="self.print()"><style>div#printPdf{display:none;}div#advertBanner{display:none;}</style>');
    docprint.document.write(printedHeader, ' - <a href=" ' + document.URL + ' " style="text-decoration:underline">' + document.URL + '</a>');
    docprint.document.write(content);
    docprint.document.write('</body></html>');
    docprint.document.close();
    docprint.focus();
}

function loadDynamicContent(siteHome, pageType, objectId, year, scriptToRun) {
    var params = new Array();
    params[0] = siteHome;    
    params[1] = pageType;
    params[2] = objectId;
    params[3] = year;
    params[4] = scriptToRun;
    
    DynamicContentGenerator.getDynamicContent(params, updateDynamicContent);
}

function updateDynamicContent(dataMap) {
    var toRun = null;
    for (var key in dataMap) {
        var data = dataMap[key];
        if (key == 'script') {
            toRun = data;
        } else {
            var newDiv = document.createElement("div");
            newDiv.innerHTML = data;
            var container = document.getElementById(key);
            container.appendChild(newDiv);
        }
    }
    if (toRun) {
        eval(toRun);
    }
}