/**
 * @author ds
 * @copyright Welke Online GmbH & Co. KG, 2009
 * @since 03/06/2009
 * 
 * JavaScript support functions for product_info.php
 */

var http;
var optionCount;
var sortArray;
var optName;
var values;

//create xmlhttprequest for ajax
if (window.XMLHttpRequest) 
{
   http = new XMLHttpRequest();
} 
else if (window.ActiveXObject) 
{
   http = new ActiveXObject("Microsoft.XMLHTTP");
}

/**
 * Function queries database for product IDs that equals user's selection
 * @param {Object} paramId
 */
function makeSelection(theForm)
{
    var optValues = getOptionValues(theForm);
    var optValuesNew;
    
    try
    {
        optValuesNew = optValues.replace(/undefiened/gi,"");
    }
    catch (e)
    {
        optValuesNew = '';
    }
    
    values = optValuesNew;
    
    if (values)
    {
        if (http != null) 
        {
            http.open('GET', 'welkeHelper.php?opt='+values+'&pids='+document.getElementById('pids').value, true);
            http.onreadystatechange = productToDisplay;
            http.send(null);
        }
    }   
}

/**
 * Function returns values of all <option>-Tags
 * @return <option> values as comma-seperated string
 */
function getOptionValues(tF)
{
    var optionValues = '';
    var options;
    options = tF.getElementsByTagName('option')
    
    for (var i=0; i<options.length; i++)
    {
        if (options[i].selected == true && options[i].value != '0')
        {
            if ((i+1) == options.length) 
            {
                optionValues += options[i].value;
            }
            else
            {
                optionValues += options[i].value+',';
            }
        }
    }

    return optionValues;
}

/**
 * Function evaluates json-array returned by server and displays corresponding products
 * @return nothing
 */
function productToDisplay()
{
    var json_productIds;
    var productIds;
    
    if (http.readyState == 4)
    {
        json_productIds = http.responseText;      
        productIds = eval('(' + json_productIds + ')');
        
        showProducts(productIds);
    }
}

/**
 * Function shows options depending on user's selection
 * @param {Object} pId IDs of products
 */
function showProducts(ajaxResult)
{
    var optReturn = ajaxResult[0].optid.split("%");
    
    var selOpt = values.split(',');
    
    removeOptions(optReturn);
    
    //create new options
    for (i = 0; i < optReturn.length; i++) 
    {
        var optArray = optReturn[i].split(":");
        
        if (!isNaN(optArray[0])) 
        {
            var optToDisplay = optArray[1].split(",");
            
            for (y=0; y<optToDisplay.length;y++)                
            {                
                var optCnt = optToDisplay[y].split("_"); 
                
                var theTxt;
                if (titleArray[optCnt[0]] != null) {
                    theTxt = titleArray[optCnt[0]];//replaceUmlauts(optCnt[1], 0);
                }
                if (backArray[optCnt[0]] != null) {
                    theTxt = backArray[optCnt[0]];//replaceUmlauts(optCnt[1], 0);
                }        
                var newOption = document.createElement("option");    
                var optAttribute = document.createAttribute("value");
                optAttribute.nodeValue = optCnt[0];
                newOption.setAttributeNode(optAttribute);
                var opt2Attribute = document.createAttribute("id");
                opt2Attribute.nodeValue = 'option'+optCnt[0];
                newOption.setAttributeNode(opt2Attribute);
                
                for (a=0; a<selOpt.length; a++)
                {
                    if (selOpt[a] == optCnt[0])
                    {
                        var opt3Attribute = document.createAttribute("selected");
                        opt3Attribute.nodeValue = 'selected';
                        newOption.setAttributeNode(opt3Attribute);        
                    }
                }
                
                var optText = document.createTextNode(theTxt);
                newOption.appendChild(optText);             
                document.getElementById('selectid' + optArray[0]).appendChild(newOption);
            }
        }
    }
    
    showImages(optReturn);
}   

function removeOptions(opt)
{
    //delete otions
    //create new options
    for (i = 0; i < opt.length; i++)
    {
        var optArray = opt[i].split(":");
        var count = document.getElementById('selectid' + optArray[0]).options.length;
        for (x = 0; x < count; x++) {
            document.getElementById('selectid' + optArray[0]).options[0] = null;            
        }
    }
} 

function showImages(opt)
{
    opt1 = document.getElementById('selectid1').options;
    
    try
    {
        opt2 = document.getElementById('selectid2').options;
    }
    catch (e)
    {
        opt2 = '';
    }
    
    
    
    var imgID = new Array;
    for (i = 0; i < opt1.length; i++) 
    {
        if (opt1[i].selected == true)
        {
            imgID.push(opt1[i].value);
        }
    }
    
    if (opt2 != '') {
        for (i = 0; i < opt2.length; i++) {
            if (opt2[i].selected == true) {
                imgID.push(imgID[0] + '_' + opt2[i].value);
            }
        }
    }      
    
    var images = getElementsByClassName('prodImg');
    
    for (z=0; z<images.length; z++)
    {
        images[z].style.display = 'none';
    }
    
    for (y=0; y<imgID.length; y++)
    {
        var disImg = getElementsByClassName('optionimg'+imgID[y]);
        for (x=0; x<disImg.length; x++)
        {
            disImg[x].style.display = 'inline';
            if (y==0 && x==0)
            {
                disImg[x].firstChild.style.width = '385px';
            }
            
            if (y+1==imgID.length && x+1==disImg.length)
            {
                disImg[x].firstChild.style.marginRight = '0';
            }
        }
    }      
}

function replaceUmlauts(string, index){
    var anArray = new Array(2);
    //anArray[0] = new Array("�", "�", "�", "�", "�", "�", "�");
    anArray[0] = new Array("\u00d6", "\u00f6", "\u00c4", "\u00e4", "\u00dc", "\u00fc", "\u00df");
    anArray[1] = new Array("&Ouml;", "&ouml;", "&Auml;", "&auml;", "&Uuml;", "&uuml;", "&szlig;");
    
    for (var i=0; i<anArray[index].length; i++){
        myRegExp = new RegExp(anArray[index][i],"g");
        string = string.replace(myRegExp, anArray[(index==0?1:0)][i]);
    }
    return string;
}

/**
 * sets the tabs div
 * @param {Object} divToShow
 */
function infoboxTab(divToShow)
{
    //set tab
    //var tmp = document.getElementById(divToShow);
    var divArray = getElementsByClassName('singleBox');
    for (i=0; i<divArray.length; i++)
    {
        divArray[i].style.display = 'none';
    }
    
    document.getElementById(divToShow).style.display = 'block';
    
    //set Menu
    var menu = document.getElementById('infoboxMenu');
    var menuLis = menu.getElementsByTagName('li');
    for (j=0; j<menuLis.length;j++)
    {
        menuLis[j].removeAttribute('class');
    }
    
    var liActive = divToShow.replace(/Div/g, "Li");
    var theLi = document.getElementById(liActive);
    var newClass = document.createAttribute('class');
    newClass.nodeValue = 'selectedTab';
    theLi.setAttributeNode(newClass);
}

/**
 * handles material/color selection
 * @param {Object} selForm
 */
function infoboxSelect(selId)
{
    var error = 0;
    var selOpt = 0;
    var selMaterial = 0;
    var theOptions =  document.getElementById(selId).getElementsByTagName('option');
    
    switch (selId)
    {
        case 'selection_material': 
            for (var i = 0; i < theOptions.length; i++) {
                if (theOptions[i].selected == true && theOptions[i].value == '0') {
                    error = 1;
                    break;
                }
                else{
                    if (document.getElementById('text' + theOptions[i].value) != null) {
                        document.getElementById('text' + theOptions[i].value).style.display = 'none';
                    }
        
                    if (theOptions[i].selected == true && theOptions[i].value != '0') {
                    
                        if (document.getElementById('text' + theOptions[i].value) != null) {
                            document.getElementById('text' + theOptions[i].value).style.display = 'block';
                        }
                        
                        selMaterial = theOptions[i].value;
                    }      
                }
            }
            
            if (error != 1)
            {
                var theColor =  document.getElementById('selection_color').options;//getElementsByTagName('option');
                
                for (k = 0; k < document.getElementById('selection_color').options.length; k++) {
                    if (document.getElementById('selection_color').options[k].selected == true) {
                        selOpt = theColor[k].value;
                    }
                }

                for (l = 0; l < 100; l++) { 
                    try {
                        document.getElementById('selection_color').removeChild(document.getElementById('selection_color')[1]);   
                    }                   
                    catch (e) {
                        
                    } 
                }
                
                var colorArray = combinationsArray[selMaterial].split('_');
                 
                for (x = 0; x < colorArray.length; x++) {
                    if (titleArray[colorArray[x]] != null) {

                        
                        var theTxt = titleArray[colorArray[x]];        
                        var newOption = document.createElement("option");    
                        var optAttribute = document.createAttribute("value");
                        optAttribute.nodeValue = colorArray[x];
                        newOption.setAttributeNode(optAttribute);
                        
                        /*if (selOpt == colorArray[x])
                        {
                            var opt3Attribute = document.createAttribute("selected");
                            opt3Attribute.nodeValue = 'selected';
                            newOption.setAttributeNode(opt3Attribute);        
                        }*/
                        
                        var optText = document.createTextNode(theTxt);
                        newOption.appendChild(optText);             
                        document.getElementById('selection_color').appendChild(newOption);
                    }
                }
            }
            
        break;     
        
        case 'selection_color':
            var hideImg = document.getElementById('materialDiv').getElementsByTagName('img');
            for (a=0; a<hideImg.length; a++)
            {
                hideImg[a].style.display = 'none';
            }
            
            var theMaterial = document.getElementById('selection_material').getElementsByTagName('option');
            for (var j=0; j<theMaterial.length; j++)
            {
                if (theMaterial[j].selected == true && theMaterial[j].value == '0') {
                    error = 1;
                    break;
                }
                else if (theMaterial[j].selected == true && theMaterial[j].value != '0')
                {
                    selMaterial = theMaterial[j].value;
                }
            }
            
            if (error != 1)
            {
                for (var b = 0; b < theOptions.length; b++) {
                    if (theOptions[b].selected == true && theOptions[b].value != '0') {
                        document.getElementById('image' + selMaterial + '_' + theOptions[b].value).style.display = 'block';
                    }
                }                 
            }
        break;               
    }
    
    if (error == 1) {
        alert('Stoff zuerst aussuchen!');
    }
}

/**
 * creates material depending color select field in infobox
 * @param {Object} optVal
 */
function createColorSelection(optVal)
{
    var colorArray = combinationsArray[optVal].split('_'); 
    var resultArray = titleArray;
    var selOpt;
    
    var delOpt = document.getElementById('selection_color').getElementsByTagName('option');
    alert('deloptlength: '+delOpt.length);
    for (v=0; v<delOpt.length; v++)
    {
        if (delOpt[i].selected == true)
        {
            selOpt = delOpt[i].value;
        }
        
        document.getElementById('selection_color').options[0] = null;
    }
    
    var countNewOp = 0;
    for (x=0; x<colorArray.length; x++)
    {
        if (resultArray[colorArray[x]] != null) {
            var newOption = document.createElement("option");
            var optAttribute = document.createAttribute("value");
            optAttribute.nodeValue = colorArray[x];
            newOption.setAttributeNode(optAttribute);
            var optText = document.createTextNode(resultArray[colorArray[x]]);
            newOption.appendChild(optText);
            
            if (selOpt == colorArray[x]) {
                var opt3Attribute = document.createAttribute("selected");
                opt3Attribute.nodeValue = 'selected';
                newOption.setAttributeNode(opt3Attribute);
            }
            
            document.getElementById('selection_color').appendChild(newOption);
            countNewOp ++;
        }
    }
    alert('count: '+countNewOp);
    return countNewOp;
}

function setForm()
{
    myForm = document.getElementById('cart_quantity');
    makeSelection(myForm);
}

/**
 * Function gets all <tags> with a given className
 * @param {Object} clsName the className
 * @return the <tags> as array
 */
function getElementsByClassName(clsName)
{
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++)
    {
        if(elements[i].className.indexOf(" ") >= 0)
        {
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++)
            {
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}

/**
 * deletes values of an input-field
 * @param {Object} inputName
 */
function deleteValue(inputName)
{
    var tmp = document.getElementsByName(inputName);
    for (var c = 0; c < tmp.length; c++) {
        tmp[c].value = '';
    }
}

/**
 * popup-function
 */
var pop = null;

function popup(obj,w,h) {
  var url = (obj.getAttribute) ? obj.getAttribute('href') : obj.href;
  if (!url) return true;
  w = (w) ? w += 20 : 150;  // 150px*150px is the default size
  h = (h) ? h += 25 : 150;
  var args = 'width='+w+',height='+h+',resizable';
  popdown();
  pop = window.open(url,'',args);
  return (pop) ? false : true;
}

window.onload = function() 
{
    //set pictures/color/etc in product_info
    if (document.getElementById('cart_quantity')) {
        (document.all && !window.print) ? null : setForm();
    }
    //initialize infobox
    if (document.getElementById('infobox')) 
    {
        (document.all && !window.print) ? null : infoboxTab('stylesDiv');
        document.getElementById('infobox').style.display = 'block';
    }
};
