//	default init
//	default is a reserved word so using handset as namespace

// Must be called as early as possible otherwise shadowbox cries... 
Shadowbox.init({
    language: 'en',
    players:  ['img', 'iframe', 'swf', 'qt', 'html']
});

var _animType = 1;

var _animType_top = "-25px";
var _animType_left = "-25px";

var _animType_easeIn = "easeOutCubic"; //easeOutCubic, easeOutElastic, easeOutBounce
var _animType_durIn = 700;

var _animType_easeOut = "easeOutCubic"; // easeInCubic, linear
var _animType_durOut = 500;

(function($) {

    $.handset = $.handset || {};

    var g_ready = false;
    var g_self = this;

    $.fn.handset = function() {
        return this.each(function() {
            //alert("API method called on " + this);
        });
    };

    $.handset.init = function(options) {
        var c_self = this;
        var c_ready = false;
        c_self.options = $.extend({}, $.handset.init.handsets, options);

        c_self.functions = {
            initialise: function(context) {
                context.each(function(index) {

                });
            },
            heroBrowser: function() {
				
				// Set ready
				var f_ready = true;
				
				// Swatch arrays 
				var swatch_arr = [];
				
				// Set current
				var currImage = $("#spotlight-image img");
				if(_IE6){var currImage = $("#spotlight-image span");} //IE6 has a span instead of img becuase of the pngFix, lovely
				var currColour = currImage.attr("class");
				
				var currLink = $("#selector-swatches a:first");
				currLink.addClass("selected")
				
				// Set controls and opacity
				var controls = $("#selector-swatches");
				controls.animate({"opacity": 0},0)
				
				// Add markup
				var addMarkup = $("<span><span></span></span>");
				var bgMarkup = $("<div></div>").addClass("bgMarkup");
				var topMarkup = addMarkup.clone().addClass("topMarkup");
				var bottomMarkup = addMarkup.clone().addClass("bottomMarkup");
				topMarkup.prependTo(controls);
				bottomMarkup.appendTo(controls);
				controls.wrapInner(bgMarkup);
				
				// Setup swatches
				controls.find("a").each(function(i){
				
					// Set vars
					var swatch = $(this);
					
					var colour = swatch.attr("href").split("#")[1];
					var hex = "#" + colour;
					var phoneImage = $("."+colour);
					//trace(phoneImage); // This is a good one for debugging!!!
					
					// Move and hide new images
					var imageContainer = $("#spotlight-image");
					imageContainer.prepend(phoneImage);
					
					// IE image var (is a span and not the image)
					if (_IE6){
						var phoneImage = $("span."+colour);
					}
					
					// Hide all but the first one
					if(i>0){
						swatch.animate({opacity: 0.5}, 500);
						if(_IE6){
							phoneImage.css('display', "none");
						} else {
							phoneImage.animate({opacity: 0});
							if(_animType == 1){
								phoneImage.animate({top: _animType_top}, 0);
							} else if(_animType == 2){
								phoneImage.animate({left: _animType_left}, 0);
							};
						};
					};
					
					swatch_arr.push(this);
					
					// Set colours
					swatch.css('background', hex);
					
					// attach hover states
					
					// attach click events
					swatch.click(function(){
						var clickedLink = $(this);

						// Check currColour is not the same as the selected colour
						if(currColour != colour && f_ready){
							// trace(f_ready);
							// Set rdy to false
							f_ready = false;
							// Swap z-index
							currImage.css("z-index", 1);
							phoneImage.css("z-index", 2);
							
							// Swap classes
							clickedLink.addClass("selected");
							clickedLink.animate({opacity: 1}, 500);
							
							currLink.removeClass("selected");
							currLink.animate({opacity: 0.5}, 500);
							currLink = clickedLink;
							
							if(_IE6){
								currImage.css({"display": "none", "visibility": "hidden"})
								phoneImage.css({"display": "block", "visibility": "visible"})
								currImage = phoneImage;
								currColour = colour;
								f_ready = true;
							} else {
								// Animate in/out
								
								if(_animType == 1){
																
									phoneImage.animate({opacity: 1, top: "0px"}, _animType_durIn, _animType_easeIn);
									currImage.animate({opacity: 0, top: _animType_top}, _animType_durOut, _animType_easeOut, function() {
										// Set new curr vars
										currImage = phoneImage;
										currColour = colour;
										// Set rdy to false
										f_ready = true;

									});
									
								} else if(_animType == 2){
								
									phoneImage.animate({opacity: 1, left: "0px"}, _animType_durIn,_animType_easeIn);
									currImage.animate({opacity: 0, left: _animType_left}, _animType_durOut, _animType_easeOut, function() {
										// Set new curr vars
										currImage = phoneImage;
										currColour = colour;
										// Set rdy to false
										f_ready = true;
									});
									
								}
							}
							return false;
						}
					})
					
				});

				// Move controls
				$("#spotlight-overview").after(controls);
				
				// Set width 
				//trace(swatch_arr.length)
				if(swatch_arr.length == (0 || 1)) {
					//trace("hide swatches cuase theres only 1");
					
				// if theres 3 or less
				} else if(swatch_arr.length < 3){
					var swatchWidth = $("#selector-swatches li:first").width() + 9;
					var controls_width = swatch_arr.length * swatchWidth + 9;
					
					// Set width 
					controls.css({"width": controls_width});
					// set visible
					controls.css({"visibility": "visible"});
					// animate in
					controls.animate({"opacity": 1},500)
					
				// if theres more than 3
				} else {
					var controls_width = "82px";
					
					// Set width 
					controls.css({"width": controls_width});
					// set visible
					controls.css({"visibility": "visible"});
					// animate in
					controls.animate({"opacity": 1},500)
					
				};
				
            },
            accordion: function(){
				
				// declare var for current item set later
				var currItem;

				$('#spotlight-features li').find('div').each(function(i){
					
					// setup vars
					var container = $(this);
					var trigger = container.children("h3");
					var minHeight = trigger.height();
					
					if(i == 0){
						// set first item as current
						currItem = container;
						// add open class
						container.addClass("open");
					} else {
						// hide others
						container.height(minHeight);
						// IE6 slow loading can lose the download brochure button... really hard to reproduce, guna try a nasty fix...
						if(_IE6){
							container.animate({height: minHeight}, 0, function(){
								$("#details-spotlight .spotlight-brochure").css("bottom", "10px");
							})
						}
						
					}
					
					trigger.click(function(){
						// get current item height - NOT height of clicked item
						var currItemMinHeight = $(currItem).children("h3").height();
						// Safari was fluffing heights, so we have to get it again on click
						// Height of "P" +  "h3" + custom padding (might change)
						var	contentHeight = container.children("p").height() + trigger.height() + 15;
						// If current item is not the same as the one clicked then do stuff....
						if(currItem != container){
							if(currItem != null){
								// hide current item
								currItem.animate({height: currItemMinHeight}, 300);
								// show clicked item
								container.animate({height: contentHeight}, 500, "easeOutQuad");
								// swap classes
								currItem.removeClass("open");
								container.addClass("open");
								// set new current
								currItem = container;
							} else {
								container.animate({height: contentHeight}, 500, "easeOutQuad");
								container.addClass("open");
								currItem = container;
							}
						// If current item is same as clicked
						} else if (currItem == container) {
							currItem.animate({height: currItemMinHeight}, 300);
							currItem.removeClass("open");
							currItem = null;
						// If there is no current item
						};
						return false;
					});
					// Lazy hover?
					trigger.hover(
						function(){
							$(this).css({color: '#660066', cursor: 'pointer'});
						},
						function(){
							$(this).css({color: '#96078E'});
						}
					);
					
				});				
            },
            configureShadowbox: function() {
            
				$("#phone-details-other .shadowIframe").each(function(){
					
					var anchors = $(this);
					// the following was setup to hide the h3 whilst cufon kicks in
					// IE6 doesnt like setting alpha on this text becuase of its container (cufon or not)
					Shadowbox.setup(anchors, {
						title: "",
							overlayColor: '#fff',
							displayNav: false,
							width: "600",
							height: "600"
							
					})
				});
				
				$("#phone-details-other .shadowVideo").each(function(){
					var anchors = $(this)
					
					//if(!anchors.attr("href").split("kanvp.swf")[1] != null){
					Shadowbox.setup(anchors, {
						title: "",
						overlayColor: '#fff',
						displayNav: false,
						width: "480",
						height: "285",
						player: "iframe"
					})
					
				});
            
				$(".shadowLinks").each(function(){
					var anchors = $(this).find("a");
					// the following was setup to hide the h3 whilst cufon kicks in
					// IE6/7 doesnt like setting alpha on this text becuase of its container (cufon or not)
					Shadowbox.setup(anchors, {
						onOpen: function(){ 
							// Hide IE6 text, enable alpha filter for testing
							if (_IE6 || _IE7) {
								$("#sb-title h3").css({'filter': 1, 'display': 'none'})
							} 
							// Hide text using animate
							$("#sb-title h3").animate({opacity: 0},0); 
						},
						onChange: function(){ 
							// Hide IE6 text, enable alpha filter for testing
							if (_IE6 || _IE7) {
								$("#sb-title h3").css({'filter': 1, 'display': 'none'})
							} 
							// Hide text using animate
							$("#sb-title h3").animate({opacity: 0},0); 
						},
					    onFinish: function(){ 
							// whilst H3 is still hidden use cufon to replace text
							Cufon.replace("#sb-title h3");
							// Animate H3 back in
							$("#sb-title h3").animate({opacity: 1},500, function(){
								// show text in IE6, no need to fade, buggy browser!
								if (_IE6 || _IE7) {
									$(this).css({'filter': 0, 'display': 'block'})
								}
							});
						},
						overlayColor: '#fff',
						gallery: "Gallery",
						slideshowDelay: "0",
						displayNav: 'true'
					});
				});
            },
            configureExternalLinks: function(){
				$("body").click(function(event) {
					if ($(event.target).is('a') || $(event.target).parents('a').size() > 0) {
						var anchor;
						if ($(event.target).is('a')) {
							anchor = $(event.target);
						}
						else {
							anchor = $(event.target).parents('a');
						}
						//if (anchor[0].hostname !== location.hostname &&  !($(anchor).hasClass('internal'))) {
						if($(anchor[0]).hasClass("popup")){
							//window.open(anchor[0].href);
							var link = anchor[0];
							var title = $(link).attr("title");
							NewWindow(link.href,title,'550','550','no');
							return false;
						}
					}
				});
				// add "opens in new window" to external links (newWindow defined on generic.master)
				$("a[href*='http']:not([href*='"+location.hostname+"'])").each(
				function() {
					var title = $(this).attr("title");
					var titleNewWindow = title + " - ";// + newWindow;
					$(this).attr("title", titleNewWindow);
				});
            }
        };
        
        c_self.functions.initialise($("body"));
        c_self.functions.heroBrowser();
        c_self.functions.accordion();
		c_self.functions.configureShadowbox();
		//c_self.functions.configureExternalLinks();
        c_ready = true;
    };
    
    // This is quick to type: trace("my console text")
    function trace(logtext) {
		try {
			if (console && console.log) {
				console.log(logtext);
			}
		} catch (err) {
			//alert(err);
		}
	};

    // handsets
    $.handset.init.defaults = {};

    // initialise one or more instances of the class
    $(document).ready(function() {
        new $.handset.init();
        $("body").equalHeights("#side-by-side", "#side-by-side .container-rep:first", "#accessorise-it", "#accessorise-it .container-rep:first")
        $("#selector-swatches").omniFix();
    });
}); // (jQuery) was in before the closing semi-colon!?
