// Easing equation, borrowed from jQuery easing plugin
// http://gsgd.co.uk/sandbox/jquery/easing/
jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

jQuery(function( $ ){
// START SLIDER SHOW		
	$('.slideshow').cycle({
		fx: 'fade', 
		speed: 1000, 
		timeout: 5000 //, 
//		next: '.slideshow'
	});
// END SLIDE SHOW

// START FLASH PORTAL	
	// add container
	$('body').append('<div id="video_port"><div id="vp_wrap"><div id="vp_object"></div></div></div>');

	//click to view
	var vidoeSafty = "off";
	$('a.flashport').click(function(e){
									
		e.preventDefault();
		
		var fVar = $(this).text(); //.replace("[", "").replace("]", "");
		var fv = fVar.substring(fVar.indexOf('[')+1, fVar.indexOf(']'));
		var flashSite = fv.substring(0, fv.indexOf(' '));
		
		var fh = fv.substring(fv.search('h="') + 3);
		var flashH = fh.substring(0, fh.indexOf('"'));
		
		var fw = fv.substring(fv.search('w="') + 3);
		var flashW = fw.substring(0, fw.indexOf('"'));
		
		var fURL = fv.substring(fv.search('url="') + 5);
		var flashURL = fURL.substring(0, fURL.indexOf('"'));
		
		$("#video_port").css("display", "table");
		if (flashSite == "video" || flashSite == "vimeo"){
			
			$('#vp_object').html('<object width="'+flashH+'" height="'+flashW+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="'+flashURL+'" /><embed src="'+flashURL+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+flashW+'" height="'+flashH+'"></embed></object>');
//<div class="closevideo">img src="closevideo.png"</a></div>
		} else if (flashSite == "youtube"){
			
			$('#vp_object').html('<object width="'+flashW+'" height="'+flashH+'" data="http://www.youtube.com/v/DGXNB6CE_Js&amp;hl=en&amp;fs=1&amp;rel=0" type="application/x-shockwave-flash"><param name="data" value="'+flashURL+'" /><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="'+flashURL+'" /><param name="allowfullscreen" value="true" /></object>');
//<div class="closevideo">img src="closevideo.png"</a></div>
		}
		vidoeSafty = "on";
	});
	//click to close
	$('#vp_object').bind({
	  mouseleave: function() {
		// do something on mouseleave
		vidoeSafty = "out";
	  },
	  mouseenter: function() {
		// do something on mouseenter
		vidoeSafty = "over";
	  }
	});
	
	$("#vp_wrap").click(closeVideo);
	function closeVideo(){
		if(vidoeSafty == "out"){
			$('#vp_object').html("");
			$("#video_port").css("display", "none");
			vidoeSafty = "off";
		}
	}
	/*
	$("#closevideo").click(function() {
		$('#vp_object').html("");
		$("#video_port").css("display", "none");
		vidoeSafty = "off";
	});

	*/
	
// END FLASH PORTAL	


	$('.scroll').css('display', 'block');


    var $panels = $('#header .scrollcontainer > div.panel');
    var $container = $('#header .scrollcontainer');
	
	var panelArray = new Array();
	
	for(i=0;i<$('.panel').length;i++){
		  //$('.panel')[i].id  // this is the list of available elements
		  // Create some text  //  $("#divScroll").append(' '+ $('.panel')[i].id);
		  
		  panelArray[i] = $('.panel')[i].id;
		  //i++
	};
    // if false, we'll float all the panels left and fix the width 
    // of the container
    var horizontal = true;

    // float the panels left if we're going horizontal
    if (horizontal) {
        $panels.css({
            'float' : 'left',
            'position' : 'relative' // IE fix to ensure overflow is hidden
        });

        // calculate a new width for the container (so it holds all panels)
        $container.css('width', $panels[0].offsetWidth * $panels.length);
    }
    // collect the scroll object, at the same time apply the hidden overflow
    // to remove the default scrollbars that will appear
    var $scroll = $('#header .scroll').css('overflow', 'hidden');
	if ($panels.length >= "2"){
		
		$scroll
			.before('<img class="scrollButtons left" src="layouts/img/left.png" />')
			.after('<img class="scrollButtons right" src="layouts/img/right.png" />');

	}
    // handle nav selection
    function selectNav() {
        $(this)
            .parents('ul:first')
                .find('a')
                    .removeClass('selected')
                .end()
            .end()
            .addClass('selected');
    }
	var thisItem = panelArray[0];
	var prevItem = panelArray[panelArray.length-1];
	var nextItem = panelArray[1];
//	$("#divScroll").text(' '+thisItem);	
	
    $('#header .scrollnav ul').find('a').click(selectNav); // "a" to  "li"
	    // go find the navigation link that has this target and select the nav
	function fade_out(){
		//$(".scroll").fadeOut(100);
	}
    function trigger(data) {
		
		
			var el = $('#header .scrollnav ul').find('li a[href$="' + data.id + '"]').get(0);
			selectNav.call(el);
			thisItem = data.id;
	
			for(Item in panelArray){
				if(panelArray[Item] == thisItem){
					//$("#divScroll").append(' '+panelArray[Item]);
					prevItem = panelArray[Item-1];
					Item++
					nextItem = panelArray[Item++];
				}; 
			};
	
//			var hexcolor = rgb2hex($('#header #'+thisItem+'').css("background-color"));
			var rbgcolor = $('#header #'+thisItem+'').css("background-color");
			$("#header").animate({backgroundColor:rbgcolor}, 500, function() {
			//	$(".scroll").fadeIn(500);
			});
		

		//$('#header #'+thisItem+'').parent().parent().parent().animate({ backgroundColor: "#ff0000" }, 'fast');
		
//		$("#header").css({'background-color' : mycolor});
    }
	
	if (window.location.hash) {
        trigger({ id : window.location.hash.substr(1) }); 
    } else {
        $('.scrollnav ul li:first').click();// "a" to  "li"
    }
	    // offset is used to move to *exactly* the right place, since I'm using
    // padding on my example, I need to subtract the amount of padding to
    // the offset.  Try removing this to get a good idea of the effect
    var offset = parseInt((horizontal ? 
        $container.css('paddingTop') : 
        $container.css('paddingLeft')) 
        || 0) * -1;


    var scrollOptions = {
        target: $scroll, // the element that has the overflow

        // can be a selector which will be relative to the target
        items: $panels,

        navigation: '.scrollnav ul li',// "a" to  "li"

        // allow the scroll effect to run both directions
        axis: 'xy',

        onAfter: trigger, // our final callback
		
		onBefore: fade_out,
		
        offset: offset,
		
		force:true,
        // duration of the sliding effect
        duration: 500,
		//do not cycle though items at first and last
		cycle:true,

        // selectors are NOT relative to document, i.e. make sure they're unique
        prev: 'img.left', 
        next: 'img.right',
		//event:'myevent',
        // easing - can be used with the easing plugin: 
        // http://gsgd.co.uk/sandbox/jquery/easing/
        easing: 'swing'
    };
	
	
	$("#header").bind('mousewheel', function(event, delta) {
			
            var dir = delta > 0 ? 'up' : 'dn',
                vel = Math.abs(delta);
            //$("#divScroll").text(dir + ' at ' + vel);
			if (dir == "up"){
				if(prevItem){
					$('#header .scrollnav ul').find('a[href$="#'+prevItem+'"]').click();
				} else {
					$('.scrollnav ul li:last').click();
				}
			} else {
				if(nextItem){
					$('#header .scrollnav ul').find('a[href$="#'+nextItem+'"]').click();
				} else {
					$('.scrollnav ul li:first').click();
				}
			}
            return false;
	});
				
	$("#header").everyTime(15000,function(i) {
		//$("#divScroll").text(i);

		if(nextItem){
			$('#header .scrollnav ul').find('a[href$="#'+nextItem+'"]').click();
		} else {
			$('.scrollnav ul li:first').click();
		}
				

	});
	
	$('#header').serialScroll(scrollOptions);
		

    // now apply localScroll to hook any other arbitrary links to trigger 
    // the effect
    $.localScroll(scrollOptions);
	

    // finally, if the URL has a hash, move the slider in to position, 
    // setting the duration to 1 because I don't want it to scroll in the
    // very first page load.  We don't always need this, but it ensures
    // the positioning is absolutely spot on when the pages loads.
//    scrollOptions.duration = 1;
    $.localScroll.hash(scrollOptions);
	
	
	
/*	
	$('.controlled-interval', demos).find('.start').css("cursor", "pointer").click(function() {
		if (!active) {
			active = !active;
			$(this).parents("div").find('ul').everyTime(1000, 'controlled', function() {
				$(this).append("<li>New One</li>");
			});
		}
	}).end().find('.stop').css("cursor", "pointer").click(function() {
		if (active) {
			active = !active;
			$(this).parents("div").find('ul').stopTime('controlled');
		}
	}); 
	*/

	/**
	 * Most jQuery.serialScroll's settings, actually belong to jQuery.ScrollTo, check it's demo for an example of each option.
	 * @see http://flesler.demos.com/jquery/scrollTo/
	 * You can use EVERY single setting of jQuery.ScrollTo, in the settings hash you send to jQuery.serialScroll.
	 */
	
	/**
	 * The plugin binds 6 events to the container to allow external manipulation.
	 * prev, next, goto, start, stop and notify
	 * You use them like this: $(your_container).trigger('next'), $(your_container).trigger('goto', [5]) (0-based index).
	 * If for some odd reason, the element already has any of these events bound, trigger it with the namespace.
	 */		
	
	/**
	 * IMPORTANT: this call to the plugin specifies ALL the settings (plus some of jQuery.ScrollTo)
	 * This is done so you can see them. You DON'T need to specify the commented ones.
	 * A 'target' is specified, that means that #screen is the context for target, prev, next and navigation.
	 */
	 
	 
	 
	 
	 
	 
	 
	 
/************************************************************************************************************
	$('#header').serialScroll({
		target:'.scroll',
		items:'.panel', // Selector to the items ( relative to the matched elements, '#sections' in this case )
		prev:'img.prev',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
		next:'img.next',// Selector to the 'next' button (absolute too)
		axis:'xy',// The default is 'y' scroll on both ways
		navigation:'.scrollnav ul li a',
		duration:400,// Length of the animation (if you scroll 2 axes and use queue, then each axis take half this time)
		force:true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)
		
		//queue:false,// We scroll on both axes, scroll both at the same time.
		//event:'click',// On which event to react (click is the default, you probably won't need to specify it)
		//stop:false,// Each click will stop any previous animations of the target. (false by default)
		//lock:true, // Ignore events if already animating (true by default)		
		//start: 0, // On which element (index) to begin ( 0 is the default, redundant in this case )		
		//cycle:true,// Cycle endlessly ( constant velocity, true is the default )
		//step:1, // How many items to scroll each time ( 1 is the default, no need to specify )
		//jump:false, // If true, items become clickable (or w/e 'event' is, and when activated, the pane scrolls to them)
		//lazy:false,// (default) if true, the plugin looks for the items on each event(allows AJAX or JS content, or reordering)
		//interval:1000, // It's the number of milliseconds to automatically go to the next
		//constant:true, // constant speed
		
		onBefore:function( e, elem, $pane, $items, pos ){
		//	/
		//	 * 'this' is the triggered element 
		//	 * e is the event object
		//	 * elem is the element we'll be scrolling to
		//	 * $pane is the element being scrolled
		//	 * $items is the items collection at this moment
		//	 * pos is the position of elem in the collection
		//	 * if it returns false, the event will be ignored
		//	 /
			 //those arguments with a $ are jqueryfied, elem isn't.
			e.preventDefault();
			if( this.blur )
				this.blur();
		},
		onAfter:function( elem ){
			//'this' is the element being scrolled ($pane) not jqueryfied
		}
	});
*************************************************************************************************************/


	
	
});
/*
function rgb2hex(rgb) {  
  rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);  
  function hex(x) {  
   hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");  
   return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];  
  }  
  return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);  
}  
*/
