function makeCoolUrl(word,coolUrlForm){
    callAndFill(getXmlHttpObject(),"coolUrl.php?word="+encodeURIcomponent(word),coolUrlForm,"value");
}

/*
function addTableRow(tableRef){
    var tbody = document.getElementById(tableRef).getElementsByTagName("TBODY")[0];
    var row = document.createElement("TR")

    var newinput = document.createElement('input');
    var divIdName = 'my'+num+'Div';
    newinput.setAttribute('type',"text");
    newinput.setAttribute('name',"name[]");
    newinput.setAttribute('style',"width:100px;");

    var td1 = document.createElement("TD")
    td1.appendChild(newinput)
    var td2 = document.createElement("TD")
    td2.appendChild (document.createTextNode("<input type=\"text\" name=\"desc[]\" style=\"width:300px;\" />"))
    var td3 = document.createElement("TD")
    td3.appendChild (document.createTextNode("<input type=\"text\" name=\"price[]\" value=\"\" style=\"width:100px;\" />"))
    var td4 = document.createElement("TD")
    td4.appendChild (document.createTextNode("<input type=\"text\" name=\"oldPrice[]\" value=\"\" style=\"width:100px;\" />"))
    
    row.appendChild(td1);
    row.appendChild(td2);
    row.appendChild(td3);
    row.appendChild(td4);
    
    tbody.appendChild(row);
}
*/

function check(chk)
{
    if(document.getElementById('selectAll').checked==true){
        for (i = 0; i < chk.length; i++)
            chk[i].checked = true ;
        // alert('You selected items to delete. After submitting, all selected items will be deleted!');
    }else{
        for (i = 0; i < chk.length; i++)
            chk[i].checked = false ;
    }
}

function checkImages(chk)
{
    for (i = 0; i < chk.length; i++)
            chk[i].checked = true ;
}

function uncheckImages(chk){
    for (i = 0; i < chk.length; i++)
            chk[i].checked = false ;
}

function changeMainCurrSymbol(){
    var mcs = document.getElementById("main_currency_symbol").value;
    document.getElementById("show_main_curr_symbol_1").innerHTML = mcs;
    document.getElementById("show_main_curr_symbol_2").innerHTML = mcs;
}

function changeCurr2Symbol(){
    var c2s = document.getElementById("currency_2_symbol").value;
    document.getElementById("show_curr_2_symbol").innerHTML = c2s;
}

function changeCurr3Symbol(){
    var c3s = document.getElementById("currency_3_symbol").value;
    document.getElementById("show_curr_3_symbol").innerHTML = c3s;
}

function addCategoryFields(addText, hideText){
    if (categoryFields.style.display=='none'){
        categoryFields.style.display='inline';
        document.getElementById('addCategoryLink').firstChild.data = hideText + ' <<';
        document.getElementById('newCategory').focus();
    } else {
        categoryFields.style.display='none';
        document.getElementById('addCategoryLink').firstChild.data = addText + ' >>';
    }
}

function addProducerFields(addText, hideText){
    if (producerFields.style.display=='none'){
        producerFields.style.display='inline';
        document.getElementById('addProducerLink').firstChild.data = hideText + ' <<';
        document.getElementById('newProducer').focus();
    } else {
        producerFields.style.display='none';
        document.getElementById('addProducerLink').firstChild.data = addText + ' >>';
    }
}

function addLocationFields(addText, hideText){
    if (locationFields.style.display=='none'){
        locationFields.style.display='inline';
        document.getElementById('addLocationLink').firstChild.data = hideText + ' <<';;
        document.getElementById('newLocation').focus();
    } else {
        locationFields.style.display='none';
        document.getElementById('addLocationLink').firstChild.data = addText + ' >>';;
    }
}

function loadPaymentForms(){
    showHideLoadingAnimation('loadingPaymentImage');
    var xmlHttp = getXmlHttpObject();
    //alert(baseUrl);
    callAndFill(xmlHttp,baseUrl+'/frontend/subpages/gui/payment-forms-gui.php?from=ajax',document.getElementById('paymentForms'),'innerHTML');
}

function loadFormForUser(customer){
    for (i=0; i<10; i++){
        if (document.getElementById('customers'+i)){
            document.getElementById('customers'+i).style.display='none';
        }
    }
    //document.getElementById('customers'+customer).style.display='block';
    if (customer==1 || customer==3){
        $('#customers1').slideDown('slow');
        if (customer==3){
            document.getElementById('customers3').style.display='block';
        }
    } else {
        $('#customers'+customer).slideDown('slow');
    }
    
}

function loadDeliveryAddress(formId){
    for (i=0; i<10; i++){
        if (document.getElementById('delivery'+i)){
            document.getElementById('delivery'+i).style.display='none';
        }
    }
    //document.getElementById('payment'+formId).style.display='block';
    $('#delivery'+formId).slideDown('slow');
}

function changePaymentMethod(formId){
    for (i=0; i<10; i++){
        if (document.getElementById('payment'+i)){
            document.getElementById('payment'+i).style.display='none';
        }
    }
    //document.getElementById('payment'+formId).style.display='block';
    // if (document.getElementById('paymentDescription'+formId).innerHTML!=""){
        $('#payment'+formId).slideDown('slow');
    //}
}

function login(nameElId,pswElId){
    showHideLoadingAnimation('loginLoadingAnimation');
    
    var nameElement = document.getElementById(nameElId);
    var pswElement = document.getElementById(pswElId);
    var loadForm = document.getElementById('loginForm');
    
    var xmlHttp = getXmlHttpObject();
    var url = baseUrl + "/frontend/processing/ajax/auth/login.php";
    var params = "type=client&login=" + encodeURIComponent(nameElement.value)
                    + "&password=" + encodeURIComponent(pswElement.value);
    
    xmlHttp.open("POST", url, true);

    //Send the proper header information along with the request
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.onreadystatechange = function() {//Call a function when the state changes.
	if(xmlHttp.readyState == 4){
                if (xmlHttp.status == 200) {
                    if (xmlHttp.responseText == 'failed'){
                        showHideLoadingAnimation('loginLoadingInformation');
                        alert('failed');
                    } else {
                        // callAndFill(xmlHttp,baseUrl+'/frontend/processing/ajax/auth/loginWindow.php?from=ajax',loadForm,'innerHTML');
                        location.href = baseUrl + '/my-account';
                    }
                } else {
                    alert('Error, status: ' + xmlHttp.status +', response text: ' + xmlHttp.responseText);
                }
        }
    }
    xmlHttp.send(params);
}

function logout(){
    showHideLoadingAnimation('loginLoadingAnimation');
    var loadForm = document.getElementById('loginForm');
    
    var xmlHttp = null;
    xmlHttp  = getXmlHttpObject();
    var url = baseUrl+'/frontend/processing/ajax/auth/logout.php?from=ajax';
    var stamp = new Date();
    url = url + '&executionTimeToPreventCaching=' + stamp.getYear()+stamp.getMonth()+stamp.getDay()+stamp.getHours()+stamp.getMinutes()+stamp.getSeconds();
    xmlHttp.open("GET", url, true);

    xmlHttp.onreadystatechange = function() {//Call a function when the state changes.
	if(xmlHttp.readyState == 4){
                if (xmlHttp.status == 200) {
                    if (xmlHttp.responseText == 'success'){
                        window.location.reload();
                    } else {
                        showHideLoadingAnimation('loginLoadingAnimation');
                        alert('Logout failed, try again later please. If problems persist, contact our administrator.');
                    }
                } else {
                    alert('Error, status: ' + xmlHttp.status +', response text: ' + xmlHttp.responseText);
                }
        }
    }
    xmlHttp.send(null);
}

function signUp(formId){
    showHideLoadingAnimation('loading');
    var oXml = getXmlHttpObject();
    var oForm = getEl(formId);
    submitForm(oXml,formId,
               function (){
                   var resDiv = getEl('result');
                   resDiv.style.display = 'block';
                   if (oXml.responseText == 'success'){
                        for (i=0; i<oForm.length; i++){
                            oForm[i].style.backgroundColor='white';
                        }
                        alert('Registration / change of data was successfull!');
                   } else {
                       var failedFields = eval('(' + oXml.responseText + ')');
                       for (i=0; i<oForm.length; i++){
                            if (in_array(oForm[i].name,failedFields)){
                                oForm[i].style.backgroundColor='#F09682';
                            } else {
                                oForm[i].style.backgroundColor='white';
                            }
                       }
                        alert('Your registration / change of data failed! Following required fields are empty or incorrect: \n' + failedFields.join('\n'));
                   }
                   showHideLoadingAnimation('loading');
               } ,
               function (){
                   showHideLoadingAnimation('loading');
                   alert('Your registration / change of data failed! Response status: ' + oXml.status + '. Try again later,please. If problems persist, contact our administrator. ');
               });
}

function processOrder(formId){
    showHideLoadingAnimation('loading');
    var oXml = getXmlHttpObject();
    var oForm = getEl(formId);
    submitForm(oXml,formId,
               function (){
                  // returned message should look like this:
                  // "successhttp://www.myadress.com/redirect/paypal"
                  // or just simply "success"
                   if (oXml.responseText.substr(0, 7) == 'success'){
                        for (i=0; i<oForm.length; i++){
                            oForm[i].style.borderColor='#DFDFDF';
                            oForm[i].style.borderWidth='1px';
                        }
                        if (oXml.responseText.length>7 && oXml.responseText.substr(7).substr(0,4)=='http'){
                            location.href=oXml.responseText.substr(7);
                        } else {
                            location.href=baseUrl + '/thank-you';
                        }
                   } else {
                       //alert(oXml.responseText);
                       var failedFields = eval('(' + oXml.responseText + ')');
                       
                       for (i=0; i<oForm.length; i++){
                            if (in_array(oForm[i].name,failedFields)){
                                oForm[i].style.borderColor='#E63F44'; // '#F5AFB2'; //#E63F44';
                                oForm[i].style.borderWidth='2px';
                            } else {
                                oForm[i].style.borderColor='#DFDFDF';
                                oForm[i].style.borderWidth='1px';
                            }
                        }
                       alert('Your registration failed! Following required fields are empty or incorrect: \n' + failedFields.join('\n'));
                   }
                   showHideLoadingAnimation('loading');
               },
               function(){
                    showHideLoadingAnimation('loading');
                    alert('Placing order failed for unknown reason. Server response: ' + oXml.status + '. Try again later,please. If problems persist, contact our administrator.');
                });
}

function contactForm(formId,loadAnimId){
    showHideLoadingAnimation(loadAnimId);
    var oConForm = getEl(formId);
    var oXhr = getXmlHttpObject();
    submitForm(oXhr,formId,
                    function(){
                        if (oXml.responseText == 'success'){
                            for (i=0; i<oForm.length; i++){
                                oForm[i].style.backgroundColor='white';
                            }
                            alert('Your message was sent!');
                        } else {
                           var failedFields = eval('(' + oXml.responseText + ')');

                           for (i=0; i<oForm.length; i++){
                                if (in_array(oForm[i].name,failedFields)){
                                    oForm[i].style.backgroundColor='#F09682';
                                } else {
                                    oForm[i].style.backgroundColor='white';
                                }
                        }
                        alert('Sending message failed! Following required fields are empty or incorrect: \n' + failedFields.join('\n'));
                   }
                        showHideLoadingAnimation('loading');
                    },
                    function(){
                        alert(oXhr.statusText);
                    });
}

  function addSubcategory(subcatName,parentCatId,loadId){
        showHideLoadingAnimation(loadId);

        subcatElem = getEl(subcatName);
        var xmlHttp = getXmlHttpObject();
        var url = baseUrl + "/management/processing/save.php?from=ajax&subject=subcategory&action=add";
        url = addTimeToUrl(url);
        var params = "subcategoryName=" + encodeURIComponent(subcatElem.value)
                     + "&parentCategoryId=" + encodeURIComponent(parentCatId);

        xmlHttp.open("POST", url, true);

        //Send the proper header information along with the request
        xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlHttp.setRequestHeader("Content-length", params.length);
        xmlHttp.setRequestHeader("Connection", "close");

        xmlHttp.onreadystatechange = function() {//Call a function when the state changes.
            if(xmlHttp.readyState == 4){
                    if (xmlHttp.status == 200) {
                        if (xmlHttp.responseText == 'failed'){
                            alert('Inserting subcategory failed');
                        } else if (isNaN(xmlHttp.responseText)){
                            alert(xmlHttp.responseText);
                        } else {
                            // alert(xmlHttp.responseText);
                            window.location = baseUrl + '/management/private.php?menu=categories&action=edit&id=' + parseInt(xmlHttp.responseText);
                        }
                    } else {
                        alert('Error, status: ' + xmlHttp.status +', response text: ' + xmlHttp.responseText);
                    }
                    showHideLoadingAnimation(loadId);
            }
        }
        xmlHttp.send(params);
  }

function showHideCompanyForms(whoiam){
    if (whoiam==1){         // private person
        if (document.getElementById('company_name')){
            document.getElementById('company_name').style.display='none';
        }
        if (document.getElementById('ico')){
            document.getElementById('ico').style.display='none';
        }
        if (document.getElementById('dic')){
            document.getElementById('dic').style.display='none';
        }
    } else if (whoiam==3){  // company
        if (document.getElementById('company_name')){
            document.getElementById('company_name').style.display='block';
        }
        if (document.getElementById('ico')){
            document.getElementById('ico').style.display='block';
        }
        if (document.getElementById('dic')){
            document.getElementById('dic').style.display='block';
        }
    }
}

function addMoreLinks(linksDiv,emptyLink){
    linksDiv.innerHTML += '<br /><br />' + emptyLink.innerHTML;
}

function changeImageShowFileDialog(id){
    document.getElementById('image'+id).style.display='none';
    document.getElementById('file'+id).style.display='inline';
}

function leavePreviousImage(id){
    document.getElementById('file'+id).style.display='none';
    document.getElementById('image'+id).style.display='inline';
}

function showVariantSelection(id){
    document.getElementById("addButton"+id).style.display='none';
    document.getElementById("loadingAnimation"+id).style.display='inline';
    var date = new Date();
    var requestTime = date.getHours()+date.getMinutes()+date.getSeconds()+date.getMilliseconds();
    var url = baseUrl+"/frontend/processing/ajax/variantSelection.php";
    $.get(url,                                                  // url
          {productId: id, requestTime: requestTime},            // params
          function(data){                                       // success
            document.getElementById("variantSelectionElement"+id).innerHTML=data;
            $("#variantSelectionElement"+id).modal({
            opacity:50,
            overlayCss:{backgroundColor:'black'}, // The CSS styling for the overlay div
            containerId:'simplemodal-container', // The DOM element id for the container div
            containerCss:{}, // The CSS styling for the container div
            dataId:'simplemodal-data', //The DOM element id for the data div
            dataCss:{}, // The CSS styling for the data div
            minHeight:null, //The minimum height for the container
            minWidth:1000, // The minimum width for the container
            maxHeight:null, // The maximum height for the container. If not specified, the window height is used.
            maxWidth:null, //The maximum width for the container. If not specified, the window width is used.
            closeHTML:'<img src="'+baseUrl+'/images/closeModal.png" style="float:right;" />', // The HTML for the default close link. SimpleModal will automatically
                                      // add the closeClass to this element.
            closeClass:'simplemodal-close', //  The CSS class used to bind to the close event
            overlayClose:true, // Allow click on overlay to close the dialog?
            onOpen:null,
            onShow:null, // The callback function used after the modal dialog has opened
            onClose:function(dialog){
                    document.getElementById("variantSelectionElement"+id).innerHTML="";
                    $.modal.close();
                }
            });
            document.getElementById("loadingAnimation"+id).style.display='none';
            document.getElementById("addButton"+id).style.display='block';
          }
          );
    };

function setSideMenuItemVisibility(id, checked){
    document.getElementById("loadingAnimation"+id).style.display='inline';
    var date = new Date();
    var requestTime = date.getHours()+date.getMinutes()+date.getSeconds()+date.getMilliseconds();
    var url = baseUrl+"/management/processing/save.php?subject=sideMenuVisibility&requestTime="+requestTime;
    checked = checked ? 1 : 0;
    $.post(url,                                                  // url
          {id: id, checked: checked},                       // params
          function(data){                                       // success
            document.getElementById("loadingAnimation"+id).style.display='none';
          }
   );
}


function checkStepOne(){
    var form = document.getElementById('firstStep');
    form.name.style.border='none';
    form.category.style.border='none';
    form.newCategory.style.border='none';
    
    var rtn = true;
    if (trim(form.name.value)==""){
        form.name.style.border='2px solid red';
        rtn = false;
    }
    if (form.category.selectedIndex==0 && trim(form.newCategory.value)==""){
            if (form.category.selectedIndex==0){
                form.category.style.border='2px solid red';
            }
            if (trim(form.newCategory.value)==""){
                form.newCategory.style.border='2px solid red';
            }
            rtn = false;
    }
    if (!rtn){
        alert('Error');
    }
    return rtn;
}
