var LOW_STOCK_COUNT = 3;
var selectBoxPrefix = "attribute";
var img_changer;
var productsStock = 10000;

//###### Class Product

function Product(sku, size, color, attr){
    // array of data  build in html file
    this.sku = sku
    this.size = size;
    this.color = color;
    // eigenschaften nochmal als array
    this.attr = attr;

    // images of size types
    this.preview_imgs = new Array();
    this.thumb_imgs = new Array();
    this.standard_imgs = new Array();
    this.large_imgs = new Array();
    this.overview_imgs = new Array();

    // id's of element boxes
    // kleine thumbs unter dem bild
    this.preview_box_id = "";
    // farbauswahl rechts
    this.thumb_box_id = "";
    // vorschau groß
    this.standard_box_id = "";
    // zoom
    this.large_box_id = "";
    // overview
    this.overview_box_id = "";
    //##### class methods init

    this.updateBox = updateBox;
    this.generateThumbContent = generateThumbContent;
    this.generatePreviewContent = generatePreviewContent;
    this.generateStandardContent = generateStandardContent;
    this.getCurrentStandardImg = getCurrentStandardImg;
    this.getCurrentImgName = getCurrentImgName;
    this.getCurrentLargeImg = getCurrentLargeImg;
}

//##### Classmethods Product

//update content of div box
function updateBox(picType){

    if(picType == 'preview'){

    }

    if(picType == 'thumb' && this.thumb_box_id && $(this.thumb_box_id)) {
        Element.update(this.thumb_box_id, this.generateThumbContent());
    }

    if(picType == 'standard'){

    }

    if(picType == 'large'){

    }

    if(picType == 'overview'){
    }
}


function generateThumbContent(){
    if(this.thumb_imgs.length <= 1) {
        return ""
    }
    var html = "";
    html += '<ul>';
    for(var y=0; y < this.thumb_imgs.length; y++){
        if(this.thumb_imgs[y][3][0][0] != undefined) {
            html += '<li><a href="#" onclick="event_setFromThumbClick(\''+this.thumb_imgs[y][0]+'\', '+y+', true); return false;">';
            html += '<img src="'+this.thumb_imgs[y][3][0][0]+'" />';
            html += '</a></li>';
        }
    }
    html += '</ul>';
    return html;
}

function generatePreviewContent(){
    var html = new Array;
    html.push('<ul>');
    for(var y=0; y < this.preview_imgs.length; y++){
        var imgName = this.getCurrentImgName(this.preview_imgs[y]);
        html.push('<li><a href="#" onclick="event_setFromPreviewClick(\''+this.sku+'\',\''+imgName+'\'); return false;">');
        html.push('<img src="'+this.preview_imgs[y]+'" />');
        html.push('</a></li>');
    }
    html.push('</ul>');
    return html;
}

function generateStandardContent(previewName){
    var html = new Array;
    var standardName = this.getCurrentStandardImg(previewName);
    var largeName = this.getCurrentLargeImg(previewName);
    html.push('<a href="'+largeName+'" id="test" class="jqzoom" title="Zoom" style="outline-style: none; cursor: crosshair; display: block; position: relative; height: 450px; width: 295px;">'
            +'<img src="'+standardName+'" />'
            +'</a>');
    return html;
}

//ermittelt anhand von previewfile die standardfile
function getCurrentStandardImg(preview_name){
    for(var i=0; i < this.standard_imgs.length; i++){
        var standard_array = this.standard_imgs[i].split('/');
        //var preview_array = preview_name.split('/');

        var name_standard = standard_array[standard_array.length-1].split('_');
        var name_preview = preview_name.split('_');

        var name_standard_str = '';
        var name_preview_str = '';

        for(var x=0; x < name_standard.length-1; x++){
            name_standard_str += name_standard[x];
        }
        //alert(name_standard_str);
        for(var x=0; x < name_preview.length-1; x++){
            name_preview_str += name_preview[x];
        }


        if(name_standard_str == name_preview_str){
            //alert(name_standard_str+' - '+name_preview_str);
            return this.standard_imgs[i];
        }
    }
}

//ermittelt anhand von previewfile die largefile
function getCurrentLargeImg(preview_name){
    for(var i=0; i < this.large_imgs.length; i++){
        var large_array = this.large_imgs[i].split('/');
        //var preview_array = preview_name.split('/');

        var name_large = large_array[large_array.length-1].split('_');
        var name_preview = preview_name.split('_');

        var name_large_str = '';
        var name_preview_str = '';

        for(var x=0; x < name_large.length-1; x++){
            name_large_str += name_large[x];
        }
        //alert(name_standard_str);
        for(var x=0; x < name_preview.length-1; x++){
            name_preview_str += name_preview[x];
        }


        if(name_large_str == name_preview_str){
            //alert(name_standard_str+' - '+name_preview_str);
            return this.large_imgs[i];
        }
    }
}
//extrahiert filename aus url mit filename
function getCurrentImgName(imgName){
    var name = imgName.split('/');
    return name[name.length-1];
}

//###### Class ImgChanger
function ImgChanger(product_data){
    // ##### Config
    // id's of element boxes
    // kleine thumbs unter dem bild
    this.preview_box_id = "more-views";
    // farbauswahl rechts
    this.thumb_box_id = "thumb-box";
    // vorschau groß
    this.standard_box_id = "standard-img-box";
    // zoom
    this.large_box_id = "large-box";
    this.overview_box_id = "overview-box";

    // array of data was build in html file
    this.product_data = product_data

    // array of product class instances
    this.products = new Array();

    // html output
    this.html = '';

    //##### class methods init

    // get pics from product_data
    this.getPicsFromProductData = getPicsFromProductData;
    this.generateProductClasses = generateProductClasses;
    this.getProductBySku = getProductBySku;
    this.getProductsByAttributes = getProductsByAttributes;
    this.updateBoxWithHtml = updateBoxWithHtml;
}

//##### Classmethods ImgChanger

//generate Classes of Products
function generateProductClasses(){
    for(var i=0; i < this.product_data.length; i++){

        //eigenschaften des productes als array
        var attr = new Array(this.product_data[i][1], this.product_data[i][2]);

        // make instance of product
        this.products[i] = new Product(this.product_data[i][0], this.product_data[i][1], this.product_data[i][2], attr);

        // set imgs
        this.products[i].preview_imgs = this.getPicsFromProductData('preview', this.products[i].sku);
        this.products[i].thumb_imgs = this.getPicsFromProductData('thumb', this.products[i].sku);
        this.products[i].standard_imgs = this.getPicsFromProductData('standard', this.products[i].sku);
        this.products[i].large_imgs = this.getPicsFromProductData('large', this.products[i].sku);

        // sets element id's of containers for updates
        this.products[i].preview_box_id = this.preview_box_id;
        this.products[i].thumb_box_id = this.thumb_box_id;
        this.products[i].standard_box_id = this.standard_box_id;
        this.products[i].large_box_id = this.large_box_id;
        this.products[i].overview_box_id = this.overview_box_id;
    }
    if (this.products && this.products[0]) {
        this.products[0].updateBox('thumb');
    }
}

//picType -> "preview" usw.
//sku -> sku number as id of product
function getPicsFromProductData(picType, sku){
    var result_array = new Array();

    // thumb
    if(picType == 'thumb'){
        var colors = new Array();
        for(var i=0; i < this.product_data.length; i++){
            var already_in_list = false;
            for(var j=0; j < colors.length; j++){
                if(colors[j] == this.product_data[i][2]) {
                    already_in_list = true;
                    break;
                }
            }
            if(already_in_list == false) {
                colors.push(this.product_data[i][2]);
                result_array.push(this.product_data[i]);
            }
        }
    }

    // preview
    if(picType == 'preview'){
        for(var i=0; i < this.product_data.length; i++){
            if(this.product_data[i][0] == sku){
                result_array = this.product_data[i][this.product_data[i].length-1][1];
            }
        }
    }

    // standard
    if(picType == 'standard'){
        for(var i=0; i < this.product_data.length; i++){
            if(this.product_data[i][0] == sku){
                result_array = this.product_data[i][this.product_data[i].length-1][2];
            }
        }
    }

    // large
    if(picType == 'large'){
        for(var i=0; i < this.product_data.length; i++){
            if(this.product_data[i][0] == sku){
                result_array = this.product_data[i][this.product_data[i].length-1][3];
            }
        }
    }

    // overview
    if(picType == 'overview'){
        for(var i=0; i < this.product_data.length; i++){
            if(this.product_data[i][0] == sku){
                result_array = this.product_data[i][this.product_data[i].length-1][4];
            }
        }
    }

    return result_array;
}

//update content of div box
function updateBoxWithHtml(picType){
    //alert('fas');

    if(picType == 'preview'){
        Element.update(this.preview_box_id, this.html);
    }

    if(picType == 'thumb'){
        Element.update(this.thumb_box_id, this.html);
    }

    if(picType == 'standard'){
        Element.update(this.standard_box_id, this.html);
        //alert(this.standard_box_id);
    }

    if(picType == 'large'){
        Element.update(this.large_box_id, this.html);
    }

    if(picType == 'overview'){
        Element.update(this.overview_box_id, this.html);
    }
}

//GETTERS

function getProductBySku(sku){
    var prod = new Object();
    for(var i=0; i < this.products.length; i++){
        if(this.products[i].sku == sku){
            prod = this.products[i];
        }
    }
    return prod;
}

//ermittelt produkte mit bestimmten eigenschaften
function getProductsByAttributes(attr){
    var prods = new Array();

    for(var x=0; x < this.products.length; x++){
        var lastOk = 1;
        var attrMatches = 0;
        for(var a=0; a < this.products[x].attr.length; a++){

            for(var i=0; i < attr.length; i++){
                if(this.products[x].attr[a] == attr[i]){
                    attrMatches++;
                }
            }
        }
        if(attrMatches == attr.length){
            prods.push(this.products[x]);
        }else{
            lastOk = 1;
        }
    }
    return prods;
}



//###### event functions

//event von preview bild
//zeigt standard bild an
function event_setFromPreviewClick(sku, previewName){
    var prod = img_changer.getProductBySku(sku);
    img_changer.html = '';
    img_changer.html = prod.generateStandardContent(previewName).join(' ');
    img_changer.updateBoxWithHtml('standard');
    jQuery('.jqzoom').jqzoom(options);
}

// FIXME
// should be $(color_dropdown_id).fire("change"); in prototype
function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}


//event von thumb bild
//zeigt preview bilder an
function event_setFromThumbClick(sku, color_index, update_dropdown ){
    if(update_dropdown) {
        $(color_dropdown_id).options.selectedIndex = color_index+1;
        fireEvent($(color_dropdown_id),'change');
    }
    else
    {
        var prod = img_changer.getProductBySku(sku);
        if(prod.sku != undefined && prod.preview_imgs[0] != undefined) {
            img_changer.html = prod.generatePreviewContent().join(' ');
            img_changer.updateBoxWithHtml('preview');
            var img_name = this.getCurrentImgName(prod.preview_imgs[0]);
            event_setFromPreviewClick(sku, img_name);
        }
    }
}

//zeigt thumbs nach eigenschaften an
function event_showThumbsForAttributes(values_array){
    var prods = img_changer.getProductsByAttributes(values_array);
    img_changer.html = '';

    for(var i=0; i < prods.length; i++){
        img_changer.html += (prods[i].generateThumbContent());
    }
    img_changer.updateBoxWithHtml('thumb');
}



/**
 * updates stock from products configuration
 */
function updateStock()
{
    productsStock = stock;
    var selectBoxes = $$('.super-attribute-select');
    if(selectBoxes.length == 1 && selectBoxes[0].attributeId == 505) {
        productsStock = $H(productsStock).values()[0];
    }
    selectBoxes.each(function(selectBox) {
        if(selectBox.options.selectedIndex == 0) {
            if(selectBox.attributeId == 505) {
                var stockSum = 0;
                $H(productsStock).each(function(stockItem){
                    stockSum = stockSum + stockItem.value;
                });
                if(stockSum > 0) {
                    productsStock = LOW_STOCK_COUNT + 1;
                } else {
                    productsStock = 0;
                }
            } else {
                return;
            }
        } else {
            productsStock = productsStock[selectBox.options[selectBox.options.selectedIndex].value];
        }
    });
    if(selectBoxes.length == 1 && selectBoxes[0].attributeId == 76) {
        productsStock = $H(productsStock).values()[0];
    }
    if(productsStock != undefined) {
        var addToCartButton = $('product_view_button');
        var html = '';

        $$('.availability').each(function(element){
            if(productsStock > LOW_STOCK_COUNT) {
                html = inStockMessage;
                if(addToCartButton != undefined) {
                    addToCartButton.show();
                }
            }
            else if(productsStock > 0) {
                html = reducedStockMessage.replace('%d', productsStock);
                if(addToCartButton != undefined) {
                    addToCartButton.show();
                }
            }
            else {
                html = outOfStockMessage;
                if(addToCartButton != undefined) {
                    addToCartButton.hide();
                }
            }
            element.innerHTML = html;
        });
    }
}



function updateAttributes(changedAttributeId)
{
    if($(selectBoxPrefix+changedAttributeId).selectedIndex > 0)
    {
        var attributes = productsAttributes[changedAttributeId][$(selectBoxPrefix+changedAttributeId).options[$(selectBoxPrefix+changedAttributeId).selectedIndex].value];
        $H(attributes).each(function (attribute){
            $$('.attribute-value-'+attribute.key).each(function(element){element.innerHTML = attribute.value});
        });
        updateStock();

        if($(color_dropdown_id) != undefined) {
            var selected_index = $(color_dropdown_id).options.selectedIndex;
            var attribute_value = $(color_dropdown_id).options[selected_index].text.split(' +')[0].split(' -')[0];
            var product = img_changer.getProductsByAttributes(new Array(new Array(attribute_value)))[0];
            if(product != undefined) {
                event_setFromThumbClick(img_changer.getProductsByAttributes(new Array(new Array(attribute_value)))[0].sku, selected_index, false);
            }
        }

    }
}

function initThumb()
{
    event_setFromThumbClick(imageSku, 0, false);
}

function initImageChanger()
{
    img_changer = new ImgChanger(productsData);
    img_changer.generateProductClasses();
}

function chooseOptionIfOnlyOne()
{
    $$('.super-attribute-select').each(function(select) {
        if(select.options.length<=2) {
            select.options.selectedIndex = select.options.length-1;
            updateAttributes(select.attributeId);
            fireEvent(select,'change');
        }
    });
}

Event.observe(window, 'load',
    function()
    {
        initImageChanger();
        initThumb();
        chooseOptionIfOnlyOne();
    }
);

