//-- Input default values and focus function
var focusArray = 0;

function findInputs(elArray){
    var labelArray = [];
    var i = 0;
    elArray.each(function(obj){
        labelArray[i] = obj.labelText;
        i++;
    });
    $$('.product-view #product-options-wrapper dt').each(function(el){
        var dt = $(el);
        if(dt.next() && dt.next().down())
            var dd = dt.next().down();
        else
            return false;
            
        var labelName;
        var t = 0;
        if(dd.getAttribute('type') == 'text') {
            if(labelName = dt.down().innerHTML.split('<span', 1)) {
                for(i=0;i<labelArray.length;i++){
                    if(labelName == labelArray[i]) {
                        elArray[i].element = dd.identify();
                    }
                }
            }
        }
    });

    window['focusArray'] = elArray;

    
    return true;
}

function inputFocus(elArray) {
    if(elArray.length > 0) {
        if(!elArray[0].element)
            findInputs(elArray);
    
        var aChar = /\S/;
        var i = 0;
        
        elArray.each(function(obj){
            if($(obj.element)) {
                elArray[i].element = $(obj.element);
                i++;
                $(obj.element).observe('focus', function(){
                    // if(this.value == obj.initText) this.setStyle({color: obj.focusColor}).value = '';
                    // else this.select();
                    this.setStyle({color: obj.focusColor}).select();
                }).observe('blur', function(){
                    // if(this.hasClassName('required-entry') && this.value.search(aChar)==-1) this.setStyle({color: obj.initColor}).value = obj.initText;
                })/*.setStyle({color: obj.initColor})*/.value = obj.initText;
            }
        });
    }
    
    window['focusArray'] = elArray;

    return true;
}

function randOrd(){
    return (Math.round(Math.random())-0.5); 
}

function fadeIt(fadeIn, el, initTriggerTime) {
    var args = $A(arguments);
    var theDuration = initTriggerTime/500;
    var config = (fadeIn) ? {from:0, to:1, duration: theDuration} : {from:1, to:.01, duration: theDuration};
    new Effect.Opacity(el, config);
}

function randomFadeToggle(oldElements, newElements) {
    var oldArray = oldElements.sort(randOrd);
    var newArray = newElements.sort(randOrd);
    var shrinkTime = 200;
    var totalTime = 500;
    var oldArrayCount = oldArray.length;
    var newArrayCount = newArray.length;
    var oldInitTriggerTime = totalTime/oldArrayCount;
    var newInitTriggerTime = totalTime/newArrayCount;
    var shrinkDelay = (oldArrayCount+4) * oldInitTriggerTime;

    //-- set triggerTime
    var singleTriggerTime = oldInitTriggerTime;

    //-- fade out 1-by-1 old elements
    oldArray.each(function(el){
        var el = $(el);
        setTimeout(function(){
            fadeIt(false, el, oldInitTriggerTime);
        }, singleTriggerTime);
        singleTriggerTime += oldInitTriggerTime;
    });

    //-- shink old and grow hidden new
    setTimeout(function(){
        oldArray.invoke('slideUp', {transition: Effect.Transitions.sinoidal, duration: shrinkTime/1000});
        newArray.each(function(el){
           var el = $(el);
           el.insert('<div></div>').setStyle({opacity:0}).up().show(); 
        });
        newArray.invoke('slideDown', {transition:Effect.Transitions.sinoidal, duration: shrinkTime/1000});
    }, shrinkDelay);

    //-- reset trigger time
    singleTriggerTime = newInitTriggerTime;

    //-- fade in 1-by-1 new elements
    setTimeout(function(){
        newArray.each(function(el){
            var el = $(el);
            var alignIt = 0;
            setTimeout(function(){
                if(el == newArray.last()) alignIt = 1;
                fadeIt(true, el, newInitTriggerTime, alignIt);
            }, singleTriggerTime);
            singleTriggerTime += newInitTriggerTime;
        });
        
    }, shrinkDelay + shrinkTime);

}

function checkDefaultValues(oldEl){
    var requiredFields = [];
    if(focusArray){ //-- declared in pc.js
        var i = 0;
        focusArray.each(function(obj){
            // if($(obj.element)) { $(obj.element).setStyle({color:obj.focusColor});}
           if($(obj.element) && $(obj.element).up('dl') == oldEl && $(obj.element).value == obj.initText) {
               var isRequired = ($(obj.element).hasClassName('required-entry')) ? true : false;
               requiredFields[i] = {element: obj.element, initText: obj.initText, req:isRequired};
               // $(obj.element).value = '';
               $(obj.element).setStyle({color: obj.focusColor});
               i++;
           } 
        });
    }
    return (requiredFields.length > 1) ? requiredFields : false;
}

function validatePageOptions(oldEl) {
    var test = new VarienForm('product_addtocart_form');
    var requiredFields = checkDefaultValues(oldEl);
    var isValid = test.validator.validate();
    // if(requiredFields) requiredFields.each(function(obj){
    //     if(obj.req) {
    //         obj.element.value = obj.initText; 
    //         if(obj.element.hasClassName('validation-passed')) 
    //             obj.element.removeClassName('validation-passed');
    //     }
    //     else if(isValid) obj.element.writeAttribute('value', ''); 
    // });
    return isValid;
}

function showHideOptions(evt, pageId) {
    // if(evt && !Prototype.Browser.IE) evt.stop(); 
    if(evt) Event.stop(evt);
    //alert(pageId + ' : '+ curOptionsPage);
    if($('options_page_' + pageId)) {
        var oldEl = $('options_page_' + curOptionsPage);
        var newEl = $('options_page_' + pageId);
        // var oldChildren = oldEl.childElements();
        // var newChildren = newEl.childElements();
        var oldChildren = $$('#options_page_' + curOptionsPage + ' dt', '#options_page_' + curOptionsPage + ' dd');
        var newChildren = $$('#options_page_' + pageId + ' dt', '#options_page_' + pageId + ' dd');
        // ## BEGIN EDIT - David Robinson - skip pages that are empty ## //
       if(pageId != 1) { //fixes infinte loop on products that just have one options page
		   var isNextPageEmpty = (newChildren.length < 2) ? true : false; 
        while((newChildren.length < 2) && (evt != false)) {
				if(curOptionsPage < pageId) 
					pageId++;
				else 
					pageId--;
        	
        	var newChildren = $$('#options_page_' + pageId + ' dt', '#options_page_' + pageId + ' dd');
        }
		}
        // ## END EDIT ## //
        	
        var lastPageElements = $$('.product-options-bottom');
        var firstPageElements = $$('.ratings', '.no-rating', '.availability', '.add-to-links', '.shipping-info', '.product-details', '#product-price-1', '.email-friend', '.sku-title', '.product-shop > .price-box, div.quark_stuff');
        if(!evt) lastPageElements.invoke('hide');
        
        //-- validate before moving on
        if((curOptionsPage == pageId-1) || (isNextPageEmpty && (curOptionsPage == pageId-2))) {
            var isValid = validatePageOptions(oldEl);
            if(!isValid) return false;
        }

        Effect.ScrollTo('top', {duration:.5, transition: Effect.Transitions.sinoidal});
        // window.location = '#' + pageId;
        // newEl.setStyle({display:'block'});

        if(pageId == lastPage) newChildren = newChildren.concat(lastPageElements); //-- show if going to last page
        if(pageId != lastPage) oldChildren = oldChildren.concat(lastPageElements); //-- hide if not going to last page
        if(pageId == 1) newChildren = newChildren.concat(firstPageElements); //-- show if going to first page
        if(pageId != 1) oldChildren = oldChildren.concat(firstPageElements); //-- hide if not going to first page
        
        // var n = newChildren.join()
        // 
        // if(pageId == lastPage) newChildren = $$((newChildren.join(',').concat(lastPageElements.join(',')))); //-- show if going to last page
        // if(pageId != lastPage) oldChildren = $$((oldChildren.join(',').concat(lastPageElements.join(',')))); //-- hide if not going to last page
        // if(pageId == 1) newChildren = $$((newChildren.join(',').concat(firstPageElements.join(',')))); //-- show if going to first page
        // if(pageId != 1) oldChildren = $$((oldChildren.join(',').concat(firstPageElements.join(',')))); //-- hide if not going to first page

        if(pageId != curOptionsPage) randomFadeToggle(oldChildren, newChildren);
        
        curOptionsPage = pageId;
        
        return true;
    }
    
    return false;
}

function updateMainImage(data) {
    $('image').src = data.small;

    if ($$('a.product-image')[0]) {
        $$('a.product-image')[0].href = data.image;
        $$('a.product-image')[0].title = data.label;
    }
    
    return true;
}

function swapMediaGalleryImages(colorId) {
    if (Prototype.Browser.IE8) {
        colorCode = $('swatch_' + colorId).getAttribute('class').split(' ')[1];
    } else {
        colorCode = $('swatch_' + colorId).readAttribute('class').split(' ')[1];
    }

    if ($$('.more-views ul li').size() > 0) {
        $$('.more-views ul li').invoke('remove');
        $$('.more-views')[0].hide();
    }
    
    if (mediaGallery[colorCode]) {
        updateMainImage(mediaGallery[colorCode][0]);
        
        if(mediaGallery[colorCode].length > 1) {
            mediaGallery[colorCode].each(function(item) {
                // if (!item.main) {
                    $$('.more-views ul')[0].insert('<li><a rel="media_gallery" href="' + item.image + '" title="' + item.label + '" class="thumbnail-image"><img src="' + item.thumbnail + '" width="56" height="56" alt="" /></a></li>');
                    $$('.more-views')[0].show();
                // }
            });
        }
    } else {
        updateMainImage(mediaGallery['default']);
    }
    //-- product image thumbnails
    if(jQuery.fn.fancybox) { 
        var fbonstart = (jQuery('.fancybox-ie').length != 0) ? function(){if(jQuery('#fbiecssfix').length == 0) jQuery('head').append('<link id="fbiecssfix" rel="stylesheet" type="text/css" media="all" href="' + SKIN_URL + 'jquery.fancybox-1.3.1-iefix.css" />');} : null; 
    
        jQuery('a[rel=media_gallery]').fancybox({
          hideOnContentClick: true
        });
    }
    return true;
}

// updates the link on the order sample button/link
function updateOrderSampleLink(colorId) {
	if ($('order_sample_product')) {
		var parts = $('order_sample_product').href.split('sampler_color');
		if (parts.size() == 2) {
			$('order_sample_product').href = parts[0] + 'sampler_color' + '/' + colorId + '/';
			return true;
		}
	}
    
	return false;
}

/*
    function toogleZoom(){
        cl('test');
        $$('.more-views li').each(function(el){
            el.observe('mouseover', function(){
                cl(this);
                if($$('.more-views').length > 0) {
                    $$('.more-views')[0].setStyle({backgroundPosition: '98% 0'});
                }
            }).observe('mouseover', function(){
                if($$('.more-views').length > 0) {
                    $$('.more-views')[0].setStyle({backgroundPosition: '-100% 0'});
                }
            });  
        });

        return true;
    }
*/
//-- On LOAD
document.observe('dom:loaded', function() {
    //-- product image thumbnails
    if(jQuery.fn.fancybox) { 
        var fbonstart = (jQuery('.fancybox-ie').length != 0) ? function(){if(jQuery('#fbiecssfix').length == 0) jQuery('head').append('<link id="fbiecssfix" rel="stylesheet" type="text/css" media="all" href="' + SKIN_URL + 'jquery.fancybox-1.3.1-iefix.css" />');} : null; 
    
        jQuery('a[rel=media_gallery]').fancybox({
        	hideOnContentClick: true
        });
    }
    
    
    

    
    //this hides the delivery option on main prod page
    //if(jQuery('dd.delivery_option').length > 0){
    //	jQuery('dd.delivery_option').css('display','none');
    //}

/*    
    if(jQuery.browser.msie){
    	jQuery('#product_addtocart_form').submit(function(e){
    		e.preventDefault();
				doFXGTask('IEFixer');
    	});
    }
*/


});

jQuery(document).ready(function() {

    if(jQuery('#fxg_proof_info').length > 0){
    	jQuery('#select_'+jQuery('#fxgOptId').html()).val(jQuery('#fxgOptVal').html());
    	jQuery("iframe#fxg_frame").load(function() {
    		//jQuery('div.product-view').delay(1000).fadeOut('fast', function() {
    		jQuery('div.product-view').fadeOut('fast', function() {
    			jQuery('#fxg_include_container').fadeIn('fast');
    		if(jQuery.browser.msie){
    			document.getElementById('fxg_frame').contentWindow.populateExistingFXGInfo('fxg_proof_info');
    			//document.getElementsByTagName('iframe')[0].contentWindow.populateExistingFXGInfo('fxg_proof_info');
    		}else{jQuery("#fxg_frame")[0].contentWindow.populateExistingFXGInfo('fxg_proof_info');}    			
  			});
  		});
    }


    jQuery('#fxg_start_btn,#fxg_return_to_project').click(function(e){
    	e.preventDefault();
    	
    	//var oldEl = $('#options_page_' + curOptionsPage);
    	//var isValid = validatePageOptions($('#options_page_' + curOptionsPage));
    	
    	var oldEl = $('#options_page_1');
    	var isValid = validatePageOptions($('#options_page_1'));
    	
    	var curPageId = (window.location.hash) ? window.location.hash[1] : 1;
    	var isValid = validatePageOptions($('#options_page_' + curPageId));
    	if(isValid){
    	 	if(jQuery(this).attr('id') == 'fxg_return_to_project'){
    			jQuery("#fxg_frame")[0].contentWindow.populateExistingFXGInfo('fxg_saved_project_info');
    		}
    		jQuery('div.product-view').fadeOut('fast', function() {
    			jQuery('#fxg_include_container').fadeIn('fast');
  			});
  		}else{return false;}
    });

});

// we need the load event to be used in IE or else the select won't be snagged
Element.observe(Prototype.Browser.IE ? window : document, Prototype.Browser.IE ? 'load' : 'dom:loaded', function(event) {
    //-- initialize qty option value and remove element with non-value
    if ($$('dd.choose_quantity select')[0]) {
        //$$('dd.choose_quantity select option:[value=""]')[0].remove();
        //$$('dd.choose_quantity select')[0].setValue($$('dd.choose_quantity select option:first-child')[0].value);
        
        // updates the price on the product page
        opConfig.reloadPrice();
        
        $$('dd.choose_quantity select option').each(function(item) {
            item.innerHTML = item.innerHTML.replace('+', 'for ');
        });
    }
});

