/*
 * Shine - global javascript
 * Author: Ben Prebble
 * Date: 28/02/2010
*/
var shineUI = window.shineUI || {};

shineUI.render = function () {		
																																					// shineUi.render class		
	var xhr, active_module, url;
  var case_study_open = false;
	var ajax_indicator = "<div id=\"cs_indicator\"><\/div>";
  var flash_upgrade_message = "<a class=\"flashUpgrade\" href=\"http://get.adobe.com/flashplayer/\">To view this content ensure that Adobe Flash Player Version 9.115 or greater is installed.<\/a>";
  
  // detect browser capabilities (for video player - html5 or flash)
  // flash
  var flash_version = flashembed.getVersion(); 
  var flash_version_supported = flashembed.isSupported([9, 115]);      

  // html5 & mp4
  var v = document.createElement('video'); 
  // tenary - "!!" casts to boolean  
  var html5_video = typeof v.canPlayType !== "undefined" ? !!(v.canPlayType) : false;
  var mp4_supported = typeof v.canPlayType !== "undefined" ? !!(v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) : false;
  
  // flow player initialisation (triggered when case study launched)
  // flash (flowplayer) with HTML5 fallback - MP4 only
	var renderPlayer = function(){
    
    /*  
    *  if flash capable (> v.9.11)
    *    use flow player  
    *  else if html5 & mp4 capable    
    *    use HTML5
    *  else
    *    upgrade flash message 
    */
    
    // use flow player  
    if(flash_version && flash_version_supported){
      //flowplayer(".player", "\/assets\/flash\/player\/flowplayer-3.1.5.swf", {	
      flowplayer(".videoPlayer", "/assets/flash/player/flowplayer.commercial-3.1.5.swf", {	
        key: '#$7e1bf8b2ab963a8fb3e',
        clip:  {
          autoPlay: true
        },
        plugins:  {   
          controls:  { 
            all:false, 
            scrubber:true, 
            play:true, 
            mute:true,
            volume:true,				
            fullscreen:true,
            autoHide: 'always',             
            height:30,
            backgroundColor: '#000000',
            progressColor: '#515151', 
            bufferColor: '#666666',
            buttonColor: '#AEAEAE',
            backgroundGradient: 'none',
            sliderGradient: 'none',
            sliderColor: '#333333',					
            volumeSliderGradient: 'none',
            volumeSliderColor: '#333333'
          }
        }
      });
      
      
      flowplayer(".audioPlayer", "/assets/flash/player/flowplayer.commercial-3.1.5.swf", {	
        key: '#$7e1bf8b2ab963a8fb3e',
        clip:  {
          autoPlay: true
        },
        plugins:  {   
          controls:  { 
            all:false, 
            scrubber:true, 
            play:true, 
            mute:true,
            volume:true,				
           // fullscreen:true,
           // autoHide: 'always',             
            height:30,
            backgroundColor: '#f9f9f9',
            progressColor: '#515151', 
            bufferColor: '#666666',
            buttonColor: '#AEAEAE',
            backgroundGradient: 'none',
            sliderGradient: 'none',
            sliderColor: '#333333',					
            volumeSliderGradient: 'none',
            volumeSliderColor: '#333333'
          }
        }
      });
        
     
      
    }// use HTML5
    else if(html5_video && mp4_supported) {
      // swap each "a.player" with "video" and set source
      $(".player").each(function(){
        var vid_src = $(this).attr("href");
        $(this).replaceWith("<video width=\"675\" src=\""+ vid_src +"\" controls=\"controls\"><\/video>");        
      });      
    }// upgrade flash message
    else{      
      $(".player").each(function(){
        $(this).replaceWith(flash_upgrade_message);
      });
    }
	};
  
  // cycle banner to next image, in this case it's randiom as per config (triggered when case study closed)
  var cycleBanner = function(){
    $('#banner_wrapper').cycle('next');
  }
  
	// lazy load images (triggered on DOM ready and when case study launched)
	var lazyLoadImages = function(){
		$("#case_study img").not(".noLazy").lazyload({
			placeholder : "\/img\/placeholder.gif",
			effect : "fadeIn" 
		});					
	};  
  
	//////////////////////////////////////////////////////
	// RETURN ELEMENT POSITION
	//////////////////////////////////////////////////////	
	var getPos = function(id){
	var pos = $(id).offset(); 	
		if(pos !== null){
			return {
				module_left:pos.left, 
				module_top:pos.top
			};
		}
		else{
			return false;
		}
	};
	//////////////////////////////////////////////////////
	// remove case study, ajax indicator and wrapper mask from the DOM
	//////////////////////////////////////////////////////	
	var removeCaseStudy = function(){
    case_study_open = false;
		$("#xhr_error").remove();
		$("#case_study").remove();			
		$(".moduleContent").removeClass("masked");	
	};
	//////////////////////////////////////////////////////
	// DISPLAY AND POSITION CASE STUDY
	//////////////////////////////////////////////////////
	var scrollToPosition = function (active_module, window_resized) {					
		var pos = getPos($(active_module));																																	// get the position of the module
		var mo_width = 225;																																									// get module and case_study widths
		var cs_width = 695;
		var hoz_position;
																																																				// show the case study directly over and to the left or right of the module	
		if((pos.module_left + (mo_width)) < ($(window).width()/2)){																					// if the selected module right hand edge is greater than half the screen width... 	
			hoz_position = pos.module_left;																																		// ...position case study to right
		}
		else{			
			hoz_position = (pos.module_left - cs_width - 20 + (mo_width));																		// otherwise just position to left		
		}
		
		if(window_resized){																																									// if the window has been resized animate the case study horizontally
			$("#case_study_wrapper").animate({left:hoz_position},500);	
			$.scrollTo("#case_study_wrapper", {		
				easing:"easeInSine",
				duration: 500
			});				
		}
		else{																																																// otherwise position it and retrieve the case study content						
			$("#case_study_wrapper").css({"left":hoz_position+"px", "top":pos.module_top+"px"});
			getCaseStudy(url);			
			$.scrollTo("#case_study_wrapper", {		
				easing:"easeInSine",
				duration: 500
			});		
		}		
	};
	//////////////////////////////////////////////////////
	// GET CASE STUDY HTML VIA AJAX
	//////////////////////////////////////////////////////
	var displayXhrError = function (){
		if($(".moduleContent").hasClass("masked")){
			$("body").append(
				"<div id=\"xhr_error\" class=\"error\">"+
				"<h1>Sorry, an error has occured</h1>"+
				"<p>"+xhr.status+"&nbsp;"+xhr.statusText+"</p>"+
				"<p>Please reload the page and trying again</p>"+
				"<a id=\"xhr_error_close\" href=\"#\">OK<\/a><\/div>"
			);
			$("#xhr_error_close").bind("click", function(){
				removeCaseStudy();						
			});		
		}		
	};
	
	var getCaseStudy = function (url) {		
		if(xhr){xhr.abort();}																																								// if AJAX request exists abort it and start a new request		
		setTimeout(function(){
			xhr = $.ajax({
					url: url,
					success: function (data) {								
						if(data == ""){
							displayXhrError();
						}            
						$("#cs_indicator").remove();	
						$("#case_study_wrapper").html(data);
						renderPlayer();
            // lazy load case study images
						lazyLoadImages();
            case_study_open = true;
						$("#close_cs").click(function () {									
							removeCaseStudy();		
              cycleBanner();																																			// remove case study, ajax indicator and wrapper mask from the DOM
							return false;
						});																		
					},
					error:function (xhr, ajaxOptions, thrownError){
						$("#cs_indicator").remove();	
						$("#case_study_wrapper").css({"width":"225px"});							
						displayXhrError();	
					}    	
			});
		},500);
	};	
  
	//////////////////////////////////////////////////////
	// INITIALISE MODULES
	//////////////////////////////////////////////////////	
	var moduleInit = function () {	
    
		var mozborderAvailable = false;
		var webkitborderAvailable = false;
		try {
			if(document.body.style.MozBorderRadius !== undefined){
				mozborderAvailable = true;
			}
			if(document.body.style.MozBorderRadius !== undefined){
				webkitborderAvailable = true;
			}
		} catch(err) {}
		
    if($.browser.msie || $.browser.opera){																															// round corners on non-standards browsers					
			$(".moduleContent").corner("10px");
		}		
		
		//$(".moduleLink").addClass("hide");		
		
		$(".module").hover(																																									// hover states
			function () {				
				$(this).children(".moduleContent").addClass("hover");
			},
			function () {									
				$(this).children(".moduleContent").removeClass("hover");
		});							
		
		$(".module").bind("click", function () {																														// click event on module
			removeCaseStudy();																																								// remove case study, ajax indicator and wrapper mask from the DOM									
			$(".moduleContent").removeClass("hover").addClass("masked");																			// mask out all modules									
			url =  $(this).children("a.moduleLink").attr("href");																							// url for ajax request									
			var suffix = $(this).attr("id").split("_");																												// build the selector (module id)		
			active_module = "#mod_"+suffix[1];	
			
			$("#cs_indicator").remove();								
			$(this).append(ajax_indicator);																																		// append ajax indicator to DOM						
		
			scrollToPosition(active_module, false);																														// scroll to and positon			
			return false;																																											// don't follow module anchor
		});	
    
    
    //remove event and reset cursor
    $(".module.noBind").each(function(){
      $(this).unbind().css({"cursor":"default"});
      $(this).children("a").attr("href", "#").css({"cursor":"default"});		
    });
  };	
	//////////////////////////////////////////////////////
	// INITIALISE EVERYTHING
	//////////////////////////////////////////////////////	
	var init = function () {
    
    // lazy load module images
   // lazyLoadImages();
    
    // get flash player version (need > 9.11 for html5 fallback solution)
   // getFlashVersion();
    
   // browserCapabilities();
    
    // banner cycle initialisation and config
    $("#banner_wrapper").cycle({
      fx: "fade",
      random: 1,
      pause: 1,
      speed:   750, 
      timeout: 10000    
    });  

    // enable sorting - this is no longer used, need to modify and delete shine-admin.js					
		if(document.location.href.indexOf("sortable=true") != -1){																					// if "sortable" is set in URL enable sorting
			shineUI.swap().sortableInit();				
		}
		else{									
			var prevHeight;
      // re-position case study on window resize
			$(window).bind("resize", function () {		
				var height = $(window).height();
				if(prevHeight == height)
					 return; // hack to prevent recursion in IE6
				prevHeight = height;

				if(active_module !== null && active_module != undefined){
					scrollToPosition(active_module, true);
				}
			});
			
      // when clicking anywhere execept the case study content, close the case study
			$("html, body").bind('click', function(e) {			
				if($(e.target).parents("#case_study").length) {
					// if we are clicking anything on a page that has a parent of "#case_study", then do nothing (stop bubbling)         
					e.stopPropagation();
				}	else {
          // only if a case study is open
          if(case_study_open === true){
            // if we are clicking anything else, cancel any requests, close the case study etc and cycle the banner image
            if(xhr){
              xhr.abort();					
            }		
            removeCaseStudy();	
            $("#cs_indicator").remove();	
            cycleBanner();				
          } else {
            return;
          }          
        }
			});
			moduleInit();																																											// initialise modules
		}	
	}; 
	return{
		init : init
	};	
};																																																			// close shineUI.render class

$(document).ready(function () {																																					// execute on DOM ready
	shineUI.render().init();
	$(document).pngFix(); 
});

