var Homepage = new function() {
	
	//private variables
	var mobile = false;
	var basePath ="/Files/HTML5_V2/";
	var data_file = basePath + "xml/homepage.xml";
	var image_path = basePath + 'images/';
	var close_tooltip = image_path + 'close.png';
	var template;
	var tmp_holder = $('<span></span>');
	var total_sections = 0;
	
	var init = function() {
        template = $('#template');
        mobile = is_mobile();        
        $('img#loader-animation').attr('src', image_path + 'loading.gif').load(function() {
            do_teaser();
        });
	}
	
	var do_teaser = function() {		
		jQuery.ajax({
	        type: "GET",
	        url: data_file,
	        dataType: "xml",
	        success: function(xml) {
				initiate(xml);
			},
	        error: function(){
	            $('#teaser_holder').add('<h1 style="position: relative; top: 50%; left: 25%; width: 400px;">Sorry, this page does not exist.</h1>');
	        }
	    });	
	}
	
	 var initiate = function(xml) {
	    var sections = $(xml).find('section', xml);
	    total_sections = sections.length;
	    var global_headline = $(xml).find('global copy headline').text();        
        var total_images = sections.length * 2;
        var images_loaded = 0;
        
        //this is weird...
        //carousel can only only be created after all images have been loaded, and 
        //all content has been added to dom
        //create_carousel must happen in image onload callack to ensure this 
        var image_loaded = function(section_index, _section_html) {
	        images_loaded++;
	        //add the section html to the temporary holder
            tmp_holder.append(_section_html);
            
            //after the last image is loaded...
	        if(total_images == images_loaded && (section_index + 1) == sections.length) {	            
	            $('#loader-animation').fadeTo(600, 0, function() { 
	                //remove extra elements
	                $(this).remove(); 
	                $('li#template').remove();	        
	                //add all of the created HTML to the DOM at once
    	            $('#carousel').append(tmp_holder.html());                               

    	            //create the carousel animation - jCarousel
    	            create_carousel();
	            });
	        }
	    }
        
        //keep track of slide number
        var sec_count = 1;        
        
        //loop over each sections, use li#template as a 'template' for slide HTML
	    sections.each(function() {	        
	        var section = $(this);
	        var section_properties = {};
	        var section_html = template.clone();
	        section_html.removeAttr('id');	        
	        
	        var bg_img = new Image();
	        var app_img = new Image();
	        	        
	        bg_img.src = image_path + section.find('background_img').text();
		
		if(section.find('appliance_img').text()) {
			app_img.src = image_path + section.find('appliance_img').text();
	        }
	        section_properties['background_img'] = bg_img;
	        section_properties['appliance_img'] = app_img;
	        section_properties['headline'] = global_headline;
	        section_properties['subheadline'] = section.find('subheadline').text();
	        section_properties['tooltip_text'] = section.find('headline').text();
	        section_properties['link'] = section.attr('link');
		section_html.find('.teaser_bg_holder').css('background-image','url('+section_properties.background_img.src+')');
	    
	    //only show appliance area when applicable
	    if(section_properties.appliance_img) {
		section_html.find('.teaser_appliance_holder').html(section_properties.appliance_img);
	    }else{
		section_html.find('.teaser_appliance_holder').remove();
	    }
	    
	    //only show the copy area if there is text for the subheadline
            if(section_properties.subheadline) {
		section_html.find('.teaser_copy_title').text(global_headline);
		section_html.find('.teaser_copy_subtitle').text(section_properties.subheadline);
	    }
            else {
                section_html.find('.teaser_copy').remove();
            }
            
            //position tooltip            
            var tooltip_position = {left : '60%', top: '60%'};
            if(section.find('tooltip').attr('left')) tooltip_position.left = section.find('tooltip').attr('left');
            if(section.find('tooltip').attr('top')) tooltip_position.top = section.find('tooltip').attr('top');     
            
            //fill tooltip content and set absolute position when there is content
            if(section_properties.tooltip_text && section_properties.link) {
                section_html.find('.tooltip').css(tooltip_position).attr('href', section_properties.link).find('span').text(section_properties.tooltip_text);  
            }
            else {
                section_html.find('.tooltip').remove();
            }
	    
            //keep track of current slide
            section_html.find('.teaser_holder').attr('rel', sec_count);
            
            //callback on image load 
            bg_img.onload = image_loaded(section.index(), section_html);
            if(app_img) {
                app_img.onload = image_loaded(section.index(), section_html);	        	        
            }
            sec_count++;
                               
	    });
	}
	
	var getCursor = function(e) {
		var curs;
		if (e.changedTouches) {    // iPhone
			curs = e.changedTouches[0].clientX;
		} 
		else {  // all others
			curs = e.clientX;
		}
		return curs;
	}
	
	//updates the active indicator
	var update_indicators = function(carousel, item, idx, state) {	 
        // would have been nice to just use idx
        // but for some reason idx is lost if 
        // wrap is enabled
	    var real_index = parseInt($(item).find('.teaser_holder').attr('rel'));
        $('.circle', '.teaser_status_holder').removeClass('red');
        $('.circle:nth-child('+real_index+')').toggleClass('red');
	}
	
	var create_carousel = function() {
	    //swipe vars
	    var start = 0;
	    var stop = 0;
	    var displacement = 0;
	    
	    //bind custom carousel sliding events
	    function init_events(carousel) {
	        
		    $('#next').bind('click', function() {
		        carousel.next();
		        return false;
		    });

		    $('#prev').bind('click', function() {
		        carousel.prev();
		        return false;
		    });
		    
		    //bind swipe events to the carousel container to traverse slides via swipe motion
    		var image_swiper = jQuery('body').find('.jcarousel-skin-elux:first')[0];
    		
    		//just get the position of swipe start
    		image_swiper.addEventListener('touchstart', function(e) {
	    	        start = getCursor(e);
    		}, false);
    		
    		//determine the direction of swipe and go to appropriate slide
    		image_swiper.addEventListener('touchend', function(e) {
    		    stop = getCursor(e);
    			displacement = Math.abs(start-stop);
    			if(displacement > 5) {
    				difference = start - stop;
    				if(difference > 0) {
    				    carousel.next();
    				}
    				else if(difference < 0) {
    				    carousel.prev();
    				}
    			}
    		}, false);
    		
    		//add the indicators to the widget
    		var indicators_width = total_sections * 15;
    		var indicators = $('<div class="teaser_status_holder"></div>').css('marginLeft', ('-' + (indicators_width / 2) + 'px'));
    		$('div.jcarousel-skin-elux').append(indicators);
    		indicators.css('width', indicators_width + 'px')
    		for(var i = 0; i < total_sections; i++) {
    		    indicators.append('<div class="circle '+ ((i == 0) ? 'red' : '') +'"></div>');
		    }
    		
		};

        //initiallize carousel, initiallize custom listeners definied in init_events
	    $("#carousel").jcarousel({
	        scroll: 1, //how many elements per slide
	        auto : 5, //autoscroller every 4 seconds	        
	        initCallback: init_events, //bind events after initiated	    
	        buttonNextHTML: null, // This tells jCarousel NOT to autobuild prev/next buttons
	        buttonPrevHTML: null, // This tells jCarousel NOT to autobuild prev/next buttons
	        //update indicators
	        wrap : 'circular',
            itemVisibleInCallback: {
                onAfterAnimation:  update_indicators
            },
            animation : 800//,
            // easing : 'easeOutBounce'
	    });
	}
	
	var is_mobile = function() {
	    if ((navigator.userAgent.match(/iPhone/i)) || 
	        (navigator.userAgent.match(/iPad/i)) || 
	        (navigator.userAgent.match(/iPod/i)) || 
	        (navigator.userAgent.match(/android/i))) {
		
			//no scrolling window
			window.document.addEventListener('touchmove', function(e) {
				e.preventDefault();
			}, false);
		
	        return true;
	    }	
	    return false;
	}
	
	this.init = init;
}();
