/****************************
Global variables
****************************/
var axflow = {}

/****************************
Startup script
****************************/
/**
Write style to hide content
*/
axflow.writeStyleForJavaScritpEnabledBrowsers = function() {
	var str = "";
	str = "<style type=\"text/css\">";
//	str += ".productTabContent {"
//	str += "    display: none;"
//	str += "}"
//	str += ".ProductImages li {"
//	str += "    display: none";
//	str += "}"
	str += "</style>"
	document.write(str);
}

axflow.writeStyleForJavaScritpEnabledBrowsers();


axflow.startup = function() {
    var productTabView = new axflow.TabView('productTabView');
    var tabView = new axflow.TabView('tabView');

    axflow.initEventRotator();
    axflow.initPageRelatedTools();
    axflow.initFileUploads();
    axflow.initProductListItems();
    axflow.initProductImages();
    axflow.initTopNavigationList();
    // Add dialogwindow to Fluidity Nonstop logotype in the footer
    axflow.dialogWindowForFooterLogo();
    //axflow.stretchZoneA3();
    axflow.formBrandModelLogic();
}
// Browser.Engine.trident: If browser is Internet Explorer (any)
if(Browser.Engine.trident) {
	window.addEvent('load', axflow.startup);
} else {
	window.addEvent('domready', axflow.startup);
}

axflow.initProductImages = function() {
    if ($defined($('imageGallery'))) axflow.imageGallery = new axflow.ImageGallery2($('imageGallery'));
}

axflow.initTopNavigationList = function() {
    $$("#topnav li").each(function(item) {
       item.addEvent('mouseenter', function() {
          item.addClass('over');
          item.setStyle('height', item.getSize().y + 'px');
       });
       item.addEvent('mouseleave', function() {
          item.removeClass('over');
       });
   }); 
}

axflow.initProductListItems = function() {
    $$('.ProductListItem').each(function(item) {
        item.addClass('clickable');
        item.addEvent('click', function() {
            document.location.href = item.getElement("a").href;
        });
    });
}

axflow.initFileUploads = function () {
	var W3CDOM = (document.createElement && document.getElementsByTagName);
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'fakefile';
	fakeFileUpload.appendChild(document.createElement('input'));
	var image = document.createElement('img');
	image.src='/images/back/btnDarkGreyBg.gif';
	fakeFileUpload.appendChild(image);
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'uploadField') continue;
		x[i].className = 'file';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
		x[i].onkeyup = function () {
			this.relatedElement.value = this.value;
		}
		x[i].onkeydown = function () {
			this.relatedElement.value = this.value;
		}
	}
}

var imgArr = null;

axflow.initEventRotator = function() {
    if ($defined($("contentPlaceHolder"))) {
        var contentEl = $("contentPlaceHolder");
        contentEl.addClass('jsEventRotator');
        axflow.axflowRotator = new axflow.EventRotator(contentArray, contentEl);
        axflow.axflowRotator.addEvent('change', function() {
            //Call flash-rotation-script here
        });

        if (Browser.Plugins.Flash.version >= 9) {

            //Show the first item immidiately
            axflow.axflowRotator.show(0);

            //Insert the flash using mootools Swiff
            var eventSwiff = new Swiff('/custom/flash/localspinner.swf', {
                id: 'eventRotator',
                width: '332',
                height: '210',
                container: $('eventsFlashContainer'),
                params: {
                    bgcolor: '#ffffff',
                    allowScriptAccess: 'sameDomain'
                },
                events: {
                    rotate: axflow.axflowRotator.rotate
                },
                vars: { images: imageArray },
                properties: {}
            });

        }
        else {
        
            //Show the first item immidiately
            axflow.axflowRotator.show(0);

            imgArr = imageArray.split(",");

            var eventsImage = new Element('img', {
                'id': 'eventsImage',
                'alt': '',
                'src': imgArr[0],
                'styles': {
                    'display': 'none'
                }
            });

            var flashContainer = $("eventsFlashContainer");
            flashContainer.appendChild(eventsImage);
            
            if (imgArr[0] != '') $('eventsImage').setStyle('display', 'block');

            var imgIdx = { counter: 0 };

            var iInterval = function() {
                this.counter++;
                if (this.counter >= imgArr.length) this.counter = 0;
                axflow.axflowRotator.rotate();

                //NEL: This image should also be faded!!
                if (imgArr[this.counter] != "") {
                    $('eventsImage').set('src', imgArr[this.counter]);
                    $('eventsImage').setStyle('display', 'block');
                }
                else {
                    $('eventsImage').setStyle('display', 'none'); 
                }
            };
            iInterval.periodical(3000, imgIdx);

        }

    }
}

// Add events to page related tools
axflow.initPageRelatedTools = function() {
	if($defined($$(".pageRelatedTools")[0])) {
		var elements = $$('.pageRelatedTools ul li a');
			elements.each(function(item, index) {
			// Print page button
			if(item.id == 'printPage') {
				item.set('href', 'javascript:void(0)');
				item.addEvent("click", function(event){
					axflow.printPage();
				});  
			}
		});
	}
}

axflow.printPage = function(){  
	if (window.print) window.print();
}

axflow.dialogWindowForFooterLogo = function() {
    var elements = $$('#footer .fluidityNonstopLogotype');
    
    if(elements!=null) {
		elements.each(function(item) {
			var dialog = new axflow.Dialog(item, {method: 'text'});
            dialog.addEvent('contentLoaded', function() {
                item.addClass('explained');
            });
            item.addEvent('mouseenter', function(e) {
                dialog.show({
                    left: e.page.x,
                    top: e.page.y 
                });
            });
            item.addEvent('mouseleave', function() {
                dialog.close();
            });
            item.addEvent('mousemove', function(e) {
                e = new Event(e);
                dialog.moveTo({
                    left: e.page.x,
                    top: e.page.y 
                });
            });
        });
    }
}

/*
axflow.initImageScroller = function() {  
     var ex6Carousel = new iCarousel("example_6_content", {  
         idPrevious: "example_6_previous",  
         idNext: "example_6_next",  
         idToggle: "undefined",  
         item: {  
             klass: "example_6_item",  
             size: 640  
         },  
         animation: {  
             type: "scroll",  
             duration: 1000,  
             amount: 1  
         }  
     });  
   
     $("thumb0").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(0)});  
     $("thumb1").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(1)});  
     $("thumb2").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(2)});  
     $("thumb3").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(3)});  
     $("thumb4").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(4)});  
     $("thumb5").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(5)});  
     $("thumb6").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(6)});  
 }
*/

axflow.stretchZoneA3 = function() {
    if($('zoneA3') == null)
        return;
    $('zoneA3').setStyle('height', 0);
    var footertop = $('footer').getPosition().y;
    var a3top = $('zoneA3').getPosition().y;
    $('zoneA3').setStyle('height', footertop - a3top - 30);
}

//window.addEvent('resize', axflow.stretchZoneA3);

function getSelectString(elementID, className, elementName, optionsHTML, label) {
    return '<label for="' + elementID + '">' + label + '</label><select id="' + elementID + '" class="' + className + '" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xforms="http://www.w3.org/2002/xforms" name="' + elementName + '">' + optionsHTML + '</select>';
}

// FORMS dynamic brand/model selector
axflow.formBrandModelLogic = function() {

    // Get content language from page
    var contentLanguage = $('contentLanguage');

    if (contentLanguage == null)
        return;

    var language = contentLanguage.innerHTML;

    // For every brand
    var brands = $$('select.brands').each(function(item, index) {

        // Try to find this brands model
        var models = $$('select.models');

        // Hide hide all models
        models.each(function(item, index) {
            item.getParent().setStyle('display', 'none');
        });

        // Get models and fill the list with javascript
        // This could be done from code behind if you could set the value of the options individually
        var request = new Request.HTML({ method: 'get', url: '/AjaxProxies/GetAllModelsHandler.ashx' });
        request.addEvents({
            'onSuccess': function(responseTree, responseElements, responseHTML, responseJavaScript) {

                // Replace current select box
                var parent = item.getParent();
                parent.set('html', getSelectString(item.id, item.className, item.name, responseHTML, item.getParent().getFirst('label').get('text')));

                // Add the onChange event
                parent.getFirst('select').addEvents({
                    'change': function() {

                        // Get brand ID from selected value
                        var BrandID_re = /\d+(?=\])/
                        var BrandID = BrandID_re.exec(this.get('value'));

                        // Get models by brand
                        var request = new Request.HTML({ method: 'get', url: '/AjaxProxies/ModelsByBrandHandler.ashx' });
                        request.addEvents({
                            'onSuccess': function(responseTree, responseElements, responseHTML, responseJavaScript) {

                                // Get model
                                var models = $$('select.models');

                                // If this brands drop down list controls several models drop down lists
                                models.each(function(item, index) {
                                    item.getParent().setStyle('display', 'inline');
                                    item.getParent().set('html', getSelectString(item.id, item.className, item.name, responseHTML, item.getParent().getFirst('label').get('text')));
                                });
                            }
                        });

                        request.send('BrandID=' + BrandID + '&Language=' + language);

                    }
                });
            }
        });

        request.send('Language=' + language);
    });
}

