/*
Some of these override earlier varien/product.js methods, therefore
varien/product.js must have been included prior to this file.
*/


//Helper function which works out which productId all passed attributes match.
//Assumes array(productIds), array(array(productIds))
Product.Config.prototype.getProductByAttributes = function(productIds, attributes){
    for (var i=0;i<productIds.length;i++) {
        var foundMatchingProduct = true;
        for (var a=0;a<attributes.length;a++) {
            if (attributes[a].indexOf(productIds[i]) == -1) {
                foundMatchingProduct = false;
                break;
            }
        }
        if (foundMatchingProduct) {
            return productIds[i];
        }
    }
    return false;
}

//Determines which simple product the currently selected configurable attributes
//map to
Product.Config.prototype.getMatchingSimpleProduct = function(){

    var childProducts =  this.config.childProducts;
    var childProductIds = [];
    for (var x in childProducts) {
        childProductIds.push(x);
    }

    var attributeProducts = [];
    for(var s=this.settings.length-1;s>=0;s--){
    	if (this.settings[s].selectedIndex == -1)
    		continue;

        var selected = this.settings[s].options[this.settings[s].selectedIndex];
        if (!selected.config){
            return false;
        }
        attributeProducts.push(selected.config.products);
    }
    return this.getProductByAttributes(childProductIds, attributeProducts);
}


Product.Config.prototype.getLowestPossiblePrice = function() {
    var childProducts =  this.config.childProducts;
    var minPrice = Infinity;
    var minPriceString = "";
    //Be careful here to return the exact input price value,
    //not some (possibly badly) converted version
    for (var x in childProducts) {
        var thisPrice = Number(childProducts[x]);
        if (thisPrice < minPrice) {
            minPrice = thisPrice;
            minPriceString = childProducts[x];
        }
    }
    return minPriceString;
}


Product.Config.prototype.updateFormProductId = function(productId){
    if (!productId) {
        return false;
    }
    var currentAction = $('product_addtocart_form').action;
    newcurrentAction = currentAction.sub(/product\/\d+\//, 'product/' + productId + '/');
    $('product_addtocart_form').action = newcurrentAction;
    $('product_addtocart_form').product.value = productId;
}


Product.Config.prototype.addParentProductIdToCartForm = function(parentProductId) {
    if (typeof $('product_addtocart_form').cpid != 'undefined') {
        return; //don't create it if we have one..
    }
    var el = document.createElement("input");
    el.type = "hidden";
    el.name = "cpid";
    el.value = parentProductId.toString();
    $('product_addtocart_form').appendChild(el);
}


Product.Config.prototype.showTierPricesBlock = function(productId) {
    config = this.config;
    $$('ul.product-pricing').each(function(label) {
        label.remove();
    });

    if (productId && config.childProductTierPriceHtml[productId]) {
        $$('div.product-options-bottom').each(function(label) {
            label.innerHTML = this.config.childProductTierPriceHtml[productId] + label.innerHTML;
        });
    }
}


Product.Config.prototype.reloadPrice = function() {
    var childProductId = this.getMatchingSimpleProduct();
    if (childProductId){
        optionsPrice.productPrice = this.config.childProducts[childProductId];
        optionsPrice.reload();
        optionsPrice.reloadPriceLabels(true);
        this.reloadFormatParts(childProductId);
//        this.updateFormProductId(childProductId);
//        this.addParentProductIdToCartForm(this.config.productId);
        this.showTierPricesBlock(childProductId);
        this.reloadSummary(optionsPrice.productPrice);
    } else {
        optionsPrice.productPrice = this.getLowestPossiblePrice();
        optionsPrice.reload();
        optionsPrice.reloadPriceLabels(false);
        this.showTierPricesBlock(false);
        this.reloadSummary(optionsPrice.productPrice);
    }
//    optionsPrice.myPrice = String(optionsPrice.productPrice);
}

/****************** Product Summary *************************/

Product.Summary = Class.create();
Product.Summary.prototype = {
	initialize: function(){
	},
	config : { 
		technikaOptId : '932',
		krosnoOptId : '934',
		krosnoIgnored : '130'
	}
}

Product.Summary.prototype.refreshOptions = function() {
	if (typeof(opConfig) != "undefined")
		opConfig.reloadPrice();
}

Product.Summary.prototype.hideAllOptions = function() {
	$$('#product-summary div.summary_row').each(function(el){
            if (el.id != "product-summary-tab-paceholder")
		el.hide();
	})
}

Product.Summary.prototype.setAndShow = function(optionId, optionPrice) {
	$('product-option-summary-price-'+optionId).innerHTML = formatCurrency(optionPrice, optionsPrice.priceFormat);
	$('product-option-summary-row-'+optionId).show();
}

Product.Summary.prototype.setAndNotShow = function(optionId, optionPrice) {
	$('product-option-summary-price-'+optionId).innerHTML = formatCurrency(optionPrice, optionsPrice.priceFormat);
}


Product.Summary.prototype.setCount = function(optionId, optionCount) {
	$('product-option-summary-count-'+optionId).innerHTML = optionCount;
}

Product.Summary.prototype.reloadPrice = function(newPrice) {
	
	if ($('product-summary-tab-price')){
		$('product-summary-tab-price').innerHTML = newPrice;
	}
	// ustawiamy label do ceny
	
//	var newLabel = new Array();
//	if ($('product-summary-tab-name')){
//		var technikaValue = $('attribute'+this.config.technikaOptId).value;
//		if (technikaValue)
//		{
//			$('attribute'+this.config.technikaOptId).select('option').each(function(label) {
//	            if (label.value == technikaValue)
//	            	newLabel.push(label.innerHTML);
//	        });
//		}
//
//		var krosnoValue = $('attribute'+this.config.krosnoOptId).value;
//		if ((krosnoValue)&&(krosnoValue != this.config.krosnoIgnored))
//		{
//			$('attribute'+this.config.krosnoOptId).select('option').each(function(label) {
//	            if (label.value == krosnoValue)
//	            	newLabel.push(label.innerHTML);
//	        });
//		}
//
//		if (newLabel.length > 0)
//			$('product-summary-tab-name').innerHTML = newLabel.join('<br/>');
//	}
}


Product.Summary.prototype.copyPrice = function(newPrice) {
	// ustawiamy cene
	if ($('product-summary-tab-price'))
	{
		var priceValue = optionsPrice.myPrice;

            if(newPrice){
                priceValue = parseFloat(priceValue) + parseFloat(newPrice);
            }
            
            priceValue = formatCurrency(priceValue, optionsPrice.priceFormat);


	    this.reloadPrice(priceValue);
	}
}

/************* Product Options Extended ********************/

Product.Options.prototype.reloadPrice = function(){
    price = new Number();
    config = this.config;
    summary = new Product.Summary();
    summary.hideAllOptions();
    skipIds = [];
    $$('.product-custom-option').each(function(element){
        var optionId = 0;
        element.name.sub(/[0-9]+/, function(match){
            optionId = match[0];
        });
        if (this.config[optionId]) {
            if (element.type == 'checkbox' || element.type == 'radio') {
                if (element.checked) {
                    if (config[optionId][element.getValue()]) {
                    	var priceFromOption = parseFloat(config[optionId][element.getValue()]); 
                        price += priceFromOption;
                        summary.setAndShow(optionId, priceFromOption);
                    }
                }
            } else if(element.hasClassName('datetime-picker') && !skipIds.include(optionId)) {
                dateSelected = true;
                $$('.product-custom-option[id^="options_' + optionId + '"]').each(function(dt){
                    if (dt.getValue() == '') {
                        dateSelected = false;
                    }
                });
                if (dateSelected) {
                	var priceFromOption = parseFloat(this.config[optionId]);
                    price += priceFromOption;
                    summary.setAndShow(optionId, priceFromOption);
                    skipIds[optionId] = optionId;
                }
            } else if(element.type == 'select-one' || element.type == 'select-multiple') {
                if (element.options) {
                    $A(element.options).each(function(selectOption){
                        if (selectOption.selected) {
                            if (this.config[optionId][selectOption.value]) {
                            	var priceFromOption = parseFloat(this.config[optionId][selectOption.value]);
                                price += priceFromOption;
                                summary.setAndShow(optionId, priceFromOption);
                            }
                        }
                    });
                }
            } else if ((element.type == 'text') && (element.hasClassName('validate-digits')) && (element.getValue().strip() != '')) {
            	var ok = false;
              	if (!/[^\d]/.test(element.getValue())) {
               		if (parseInt(element.getValue()) == 0) {
               			element.value = '';
               		} else {
               			var priceFromOption = parseInt(element.getValue()) * parseFloat(this.config[optionId]); 
               			price += priceFromOption;
               			summary.setAndShow(optionId, priceFromOption);
               			summary.setCount(optionId, parseInt(element.getValue()));
               		}
               	}
            } else if ((element.type == 'text') && (element.hasClassName('validate-integers')) && (element.getValue().strip() != '')) {
              	if (/^\s*(\+|-)?\d+\s*$/.test(element.getValue())) {
               		if (parseInt(element.getValue()) == 0) {
               			element.value = '';
               		} else {
               			var priceFromOption = parseInt(element.getValue()) * parseFloat(this.config[optionId]);
               			price += priceFromOption;
               			//summary.setAndShow(optionId, priceFromOption);
               			//summary.setCount(optionId, parseInt(element.getValue()));
                                summary.copyPrice(priceFromOption);
               		}
               	}
            } else {
               if (element.getValue().strip() != '') {
            	    var priceFromOption = parseFloat(this.config[optionId]);
                    price += priceFromOption;
                    summary.setAndShow(optionId, priceFromOption);
                 }
            }
        }
    });
    try {
        optionsPrice.changePrice('options', price);
        optionsPrice.reload();
    } catch (e) {
    }
}

/************************************************************/

Product.Config.prototype.reloadSummary = function(newPrice) {
	var productSummary = new Product.Summary();
	productSummary.reloadPrice(formatCurrency(newPrice, optionsPrice.priceFormat));
	productSummary.refreshOptions();
}

Product.OptionsPrice.prototype.reloadPriceLabels = function(productPriceIsKnown) {
    var priceLabel = '';
    if (!productPriceIsKnown) {
        priceLabel = spConfig.config.priceFromLabel;
    }

    var priceSpanId = 'configurable-price-from-' + this.productId;
    var duplicatePriceSpanId = priceSpanId + this.duplicateIdSuffix;

    $(priceSpanId).select('span.configurable-price-from-label').each(function(label) {
        label.innerHTML = priceLabel;
    });

    if ($(duplicatePriceSpanId) && $(duplicatePriceSpanId).select('span.configurable-price-from-label')) {
        $(duplicatePriceSpanId).select('span.configurable-price-from-label').each(function(label) {
            label.innerHTML = priceLabel;
        });
    }
}

/****************** ConfigurableToSimple Module - End *************************/


/*==============================================================================
 *
 *                        FRAMESTUDIO JS FUNCTIONS
 *
 *============================================================================*/


// Show framestudio
function show_studio(reloadurl){
     if(document.getElementById('radio_custom').checked)
         var dims = document.getElementById('custom_size').innerHTML;
     else
         var dims = document.getElementById('product_image_parts_formats').innerHTML;
    dims = dims.replace(/ /g, "x");
    dims = dims.split('x');
    var edge = Number(dims[0]);
    var exploaded = reloadurl.slice(6,(reloadurl.length-1));
    exploaded = exploaded.split('/');
    exploaded[(exploaded.length)-1] = edge;
    reloadurl = reloadurl.slice(0,6)+exploaded.join('/');
    this.myLightWindow.activateWindow({
        type: 'page',
	href: reloadurl,
	width: 1020,
        height: 900
    });
}
// Show frame studio after confirming frame choice
function show_studio_confimed(reloadurl){
   var frame = document.getElementById('frame_id').innerHTML;
   var exploaded = reloadurl.slice(6,(reloadurl.length-1));
   exploaded = exploaded.split('/');
   exploaded[(exploaded.length)-3] = frame;
   reloadurl = reloadurl.slice(0,6)+exploaded.join('/');
   show_studio(reloadurl);
 }
//Frame picture with selected frame, update confirm link, reload aux pics
function newframe(pic,frame,edge,fcat,product_price,div_id){
   //show loading
   document.getElementById('in_frame').style.visibility='hidden';
   document.getElementById('in_frame').style.width='0px';
   document.getElementById('out_frame').style.display = "inline";

   var source = document.getElementById('in_frame').src;
   var exploaded = source.slice(6,(source.length-1));

   //re-frame picture
   exploaded = exploaded.split('/');
   exploaded[(exploaded.length)-1] = edge;
   exploaded[(exploaded.length)-3] = frame;
   exploaded[(exploaded.length)-5] = pic;
   source = source.slice(0,6)+exploaded.join('/');
   document.getElementById('in_frame').src = source;

   //re-do confirm link
   exploaded[(exploaded.length)-7] = 'confirm';
   exploaded.push('fcat');
   exploaded.push(fcat+'/');
   var onclick = source.slice(0,6)+exploaded.join('/');
   document.getElementById('frame_cofirm_link').onclick = function(){
       FrameSlider.stop();
       confirm_frame(onclick);
   }
   var oldframe = get_frame_id();
   document.getElementById('img_'+frame).style.border ="2px solid #F86D05";
   if(Number(oldframe) != Number(frame) && document.getElementById('img_'+oldframe))
        document.getElementById('img_'+oldframe).style.border ="1px solid black";

   //reload inset info
   exploaded[(exploaded.length)-9] = 'frameinset';
   source = source.slice(0,6)+exploaded.join('/');
   new Ajax.Request(source, {
        method: 'get',
        parameters: {
        },
        onComplete: function(transport) {
            evalScripts:true,
            document.getElementById('framestudio_inset').innerHTML = '';
            document.getElementById('framestudio_inset').innerHTML = transport.responseText;
            transport.responseText.evalScripts();
        }
    });

   //set rest of the stuff
   set_frame_id(frame);
   set_price(frame,'studio_frame_price');
   set_total_price(frame, product_price, div_id);
}
//reload category contents in frame studio
function gonow(reloadurl){
    //Element.show('loadingmask');
    document.getElementById('reloaded').innerHTML = '<img id="out_preview_1" class="loading" src="/skin/frontend/default/artgeist/images/ajax-loading.gif" alt="loading..." />';
    new Ajax.Request(reloadurl, {
        method: 'get',
        parameters: {
        },
        onComplete: function(transport) {
            // Element.hide('loadingmask');
            evalScripts:true,
            document.getElementById('reloaded').innerHTML = '';
            document.getElementById('reloaded').innerHTML = transport.responseText;
            transport.responseText.evalScripts();
        }
    });
}

// Monitoring zależności wybór ramy <-> wysyłka expresowa
function checkExpressService()
{
    if($('_express_service').innerHTML)
    {
        var productOptionOut = $('product-option-out-' + $('_express_service').innerHTML),
            optionText = $('options_' + $('_frame_price').innerHTML + '_text');

        if(optionText.value != '')
        {
            var checkbox = productOptionOut.down("input[type='checkbox']")
            checkbox.checked = false;
            opConfig.reloadPrice();
            productOptionOut.hide();
        }
        else
            productOptionOut.show();
    }
}

// realod add frame contents after confirming frame choice
function confirm_frame(reloadurl){
    this.myLightWindow.deactivate();
    var frame = document.getElementById('frame_id').innerHTML;
    set_frame_id(frame);
    var exploaded = reloadurl.slice(6,(reloadurl.length-1));
    exploaded = exploaded.split('/');
    exploaded[(exploaded.length)-5] = frame;
    reloadurl = reloadurl.slice(0,6)+exploaded.join('/');
    document.getElementById('frameinfo').innerHTML = '<img id="out_preview_1" class="loading" src="/skin/frontend/default/artgeist/images/ajax-loading.gif" alt="loading..." />';
    new Ajax.Request(reloadurl, {
        method: 'get',
        parameters: {
        },
        onComplete: function(transport) {
            // Element.hide('loadingmask');
            document.getElementById('frameinfo').innerHTML = "";
            document.getElementById('frameinfo').innerHTML = transport.responseText;
            transport.responseText.evalScripts();
            checkExpressService();
        }
    });
}
// set frame_id to slected frame's id
function set_frame_id(frame){
     var field_id = document.getElementById('_frame_id').innerHTML;
     document.getElementById('frame_id').innerHTML = frame;
     document.getElementById('options_'+field_id+'_text').value = frame;
}
function set_frame_id2(frame){
     document.getElementById('frame_id').innerHTML = frame;
}
function get_frame_id(){
    var frame = document.getElementById('frame_id').innerHTML;
    return frame;
}

function get_frame_len(){
     if(document.getElementById('radio_custom').checked)
         var dims = document.getElementById('custom_size').innerHTML;
     else
         var dims = document.getElementById('product_image_parts_formats').innerHTML;
     dims = dims.replace(/ /g, "x");
     dims = dims.split('x');
     var len = 0;
     for(var i=0;i<dims.length;i++)
        len += ((Number(dims[i])*2)/100);
     return len;
}
//set price based on pic size and frame price per
function set_price(frame,div_id){
     var len = get_frame_len();
     var price = document.getElementById(frame).innerHTML;
     price = price.split(';');
     var pricePL = price[1];
     price = price[0];
     price = Number(price)*len;
     pricePL = Number(pricePL)*len;
     if(!isNaN(price)){
         document.getElementById(div_id).innerHTML = optionsPrice.formatPrice(pricePL.toFixed(2));
        if(div_id == 'frame_price'){
            var check = document.getElementById('with_frame').checked;
            if(check){
                var field_id = document.getElementById('_frame_price').innerHTML;
                price = price.toFixed(2) * 100;
                document.getElementById('options_'+field_id+'_text').value = price.toFixed();
            }
            opConfig.reloadPrice();
        }
     }
}

function update_price(){
    var frame = get_frame_id();
    if (frame){
        set_price(frame,'frame_price');
    }
}

function set_total_price(frame, product_price, div_id){
     var price = document.getElementById(frame).innerHTML;
     price = price.split(';');
     var len = get_frame_len();
     price = Number(price[1])*len + Number(product_price);
     document.getElementById(div_id).innerHTML = optionsPrice.formatPrice(price.toFixed(2));
}

function frame_toggle(check){
    var frame = document.getElementById('frame_id').innerHTML
    var field_id_f = document.getElementById('_frame_id').innerHTML;
    var field_id_p = document.getElementById('_frame_price').innerHTML;

    if(check.checked){
        var price = document.getElementById(frame).innerHTML;
        price = price.split(';');
        var len = get_frame_len();
        price = Number(price[0]) *len;
        price = price.toFixed(2) * 100;
        document.getElementById('options_'+field_id_p+'_text').value = price.toFixed();
        document.getElementById('options_'+field_id_f+'_text').value = frame;
        document.getElementById('frame_price').style.textDecoration = 'none';

    }else{
        document.getElementById('options_'+field_id_p+'_text').value = '';
        document.getElementById('options_'+field_id_f+'_text').value = '';
        document.getElementById('frame_price').style.textDecoration = 'line-through';
    }
    opConfig.reloadPrice();
    checkExpressService();
}


function dims_with_frame(){
     var dims = document.getElementById('product_image_parts_formats').innerHTML;
     dims = dims.replace(/ /g, "x");
     dims = dims.split('x');
     var width = document.getElementById('frame_width').innerHTML;
     if(width.length){
         width = width.replace(/\,/g,'.');
         width = parseFloat(width);
     }else
         width = 0;
     var lenx = 0;
     var leny = 0;
     for(var i=0;i<dims.length;i++){
        lenx +=  Number(dims[i]) + (width*2);
        leny =  (Number(dims[i+1]) > (leny + (width*2))) ? (Number(dims[i+1]) + (width*2)) : (width*2);
        i++;
     }
     var str = lenx +'x'+leny+'cm';
     return str;
}

function menu_over(obj){
    obj = $(obj);
    if(!obj.hasClassName('over') && !obj.hasClassName('selected_main'))
        obj.addClassName('over');
}

function menu_out(obj){
    obj = $(obj);
    if(obj.hasClassName('over'))
        obj.removeClassName('over');
}

function menu_change(obj,target){
    obj = $(obj);
    target = $(target);
    $$('li.selected_main').each(function(el){
        el.removeClassName('selected_main');
    })
    obj.addClassName('selected_main');
    $$('div.product-options').each(function(el){
        el.hide();
    })
    if(obj.hasClassName('over'))
        obj.removeClassName('over');
    target.show();
}
function swap_aux(source,hide){
    if (hide)
        document.getElementById('in_frame').style.display = 'none';
    else
        document.getElementById('in_frame').style.display = 'block';

    if (source){
        document.getElementById('wall').style.backgroundImage = "url('"+source+"')";
        document.getElementById('wall').style.backgroundRepeat = 'no-repeat';
    }else
        document.getElementById('wall').style.backgroundImage = 'none';

}

//
//Checks frame data consistency before submitting the form
//both frame price and frame id must be present to order
//frame
//

function check_consistency(){
     var field_id_f = document.getElementById('_frame_id').innerHTML;
     var field_id_p = document.getElementById('_frame_price').innerHTML;
     var fprice = document.getElementById('options_'+field_id_p+'_text').value;
     var fid = document.getElementById('options_'+field_id_f+'_text').value;
     if ((!fid && fprice) || (fid && !fprice)){
         //soemthing is off, disable frame
         document.getElementById('options_'+field_id_p+'_text').value = '';
         document.getElementById('options_'+field_id_f+'_text').value = '';
     }
}

function select_detial(detail){
    document.getElementById('corner').className = '';
    document.getElementById('profile').className = '';
    document.getElementById('iso').className = '';
    document.getElementById('mini').className = '';
    document.getElementById('corner_zoom').style.display = '';
    document.getElementById('profile_zoom').style.display = '';
    document.getElementById('iso_zoom').style.display = '';
    document.getElementById('mini_zoom').style.display = '';
    var zoom_id = detail.id + '_zoom';
    document.getElementById(zoom_id).style.display = 'none';
    detail.className='selected';
}

//
//====================END FRAMESTUDIO FUNCTIONS
//




   function manual_tooltip_load(){
        $$("img").findAll(function(node){
            return node.getAttribute('ondblclick');
        }).each(function(node){
            var text = new String (node.getAttribute('ondblclick'));
            text =  text.replace('return \'','').replace('\';','')
                        .replace('function ondblclick()', '').replace('{', '')
                        .replace('}', '');
            var ht = '<div class="image"><img src="' + text + '" /></div>';
            if (node.getAttribute('title')){
                if (!isNaN(parseFloat(node.getAttribute('title')))){
                    var title = $('id_' + node.getAttribute('title'));
                    if(title)
                      ht += '<div class="inner">'+ title.innerHTML +'</div>';
                }
                else{
                    var title = document.createElement('div');
                    title.innerHTML = node.getAttribute('title');
                    ht += '<div class="inner_wide">'+ title.innerHTML +'</div>';
                }
            }
            new Tooltip(node, ht);
            node.removeAttribute("ondblclick");

        });
    }
