/*
	Manages URL hashes
*/
POKE.hash = function() {
	
	var current_hash = "";
	var change_callbacks = [];
	var hash_change = function () {
		if(current_hash.toString() != pub.get().toString()) {
			for (var i=0; i < change_callbacks.length; i++) {
				change_callbacks[i](pub.get());
			};
			current_hash = pub.get();
		}
	};

	setInterval(hash_change, 250);
	
	var pub = {
		get : function(index){
			var url = document.location.hash;
			if(url.length === 0){
				return false;
			}
			var values = url.split("#/")[1];
			if(!values){
				return url;
			}
			var value = index !== undefined ? values.split("/")[index] : values && values.split("/") || false; 
			return value || false;
		},
		
		// string or array
		set : function(hash){
		    pub.go(hash);
			current_hash = this.get();
		},
		
		go : function(hash){
	    	if(hash !== undefined){
				hash = (typeof hash == 'object' && hash.length !== undefined) ? hash.join('/') : hash;
				hash = "#/" + hash;
			}else{
				hash = "#";
			}
			document.location.hash = hash;    
		},
		
		replace : function (index, value) {
			var all = this.get() || [];
			all[index]=value;
			this.set(all);
		},
		
		on_change : function (fn) {
			change_callbacks.push(fn);
		}
	};
	return pub;	
}();

POKE.dispatch = function () {
    var map = {};
    var current_section = 'index';
    var change = function(segments) {
        if(segments.length > 0 && typeof segments == 'object') {
            var new_section = segments.shift();
        }else{
            var new_section = 'index';
        }
        if (new_section != current_section && map[new_section] != undefined){
            map[new_section](segments);
            current_section = new_section;
        }
    };
    POKE.hash.on_change(change);
    return {
        add : function (hash, fn_go) {
            map[hash] = fn_go;
        },
        map : function (map) {
            for (obj in map) {
                POKE.dispatch.add(map[obj][0], map[obj][1]);
            }
        }
    };
    
}();

POKE.swf = function() {
	
	var default_flashvars = {
		debug : 0
	};
	
	var default_attributes = {
	    bgcolor : '#000000'
	};
	var default_params = {
		allowScriptAccess : 'sameDomain',
		allowFullScreen:"true",
		menu : false,
		quality : 'best',
		salign : 'tl',
		wmode : 'window'
	};
	
	return {
		embed : function (url, element_id, width, height, flashvars, params, attributes) {
			var flashvars = 	$.extend({}, default_flashvars, flashvars);
			var attributes = 	$.extend({}, default_attributes, attributes);
			var params = 		$.extend({}, default_params, params);
			if(!attributes.id) { attributes.id = element_id; }
			swfobject.embedSWF(url, element_id, width, height, "9.0.28", "/static/flash/expressInstall.swf", flashvars, params, attributes);
			setTimeout(function(){POKE.swf.focus(element_id);}, 500);
			return document.getElementById(attributes.id);
		},

		remove : function (element_id) {
			swfobject.removeSWF(element_id);
		},
		
		focus : function (element_id) {
			$('#'+element_id).focus();
		}
	};
	
}();

POKE.video = function () {
	var default_flashvars = {
		callbackClose: "POKE.video.on_close",
		controlbar:'over',
		stretching:'fill',
		autostart:'true',
		logo : POKE.settings.MEDIA_URL+'images/logo/Logo_Stripe_White.png',
        tile : POKE.settings.MEDIA_URL+'images/VR_Pattern_30.png',
        videoTitle : ''
	};
	var settings = {element_id:'page'};
	return {
		play : function (video_conf) {
		  var fv = $.extend({}, default_flashvars, video_conf || {});
			$('#'+settings.element_id).hide();
			var fullscreenNode = $('<div id="fullscreen_video"></div>')
			$('body').addClass('full').append(fullscreenNode);
			var width = '100%', height = width;
			if(jQuery.browser.safari){
			  // Rapid resizing of embedded swf object crashes webkit on mac
			  // Employ a slightly slower responding way of resizing embed object
			  var width = $(window).width();
			  var height = $(window).height();
			  var fullscreenNodeResize = function(){
			    $("#fullscreen_video").width($(window).width()+"px");
			    $("#fullscreen_video").height($(window).height()+"px");
			    setTimeout(fullscreenNodeResize, 100);
			  }; 
			  fullscreenNodeResize();
			}
			swfobject.embedSWF(POKE.settings.LOCAL_MEDIA_URL+'flash/player.swf', 'fullscreen_video', width, height, "9.0.28", "/static/flash/expressInstall.swf", fv, {base:POKE.settings.MEDIA_URL, bgcolor: "#000000"});
		},
		on_close : function () {
			POKE.hash.go('index');
		},
		revert_to_html : function () {
			$('#'+settings.element_id).show();
			$('body').removeClass('full').find('#fullscreen_video').remove();
		}
	};
}();

POKE.gallery = function () {
	var default_flashvars = {
		closeFunction: "POKE.gallery.on_close"		
	};
	var settings = {element_id:'page'};
	return {
		display : function (gallery_xml) {
		    var gallery_conf = {xmlURL:gallery_xml};
		    var fv = $.extend({}, default_flashvars, gallery_conf || {});
			$('#'+settings.element_id).hide();
			$('body').addClass('full').append('<div id="fullscreen_gallery"></div>');
			POKE.swf.embed(POKE.settings.LOCAL_MEDIA_URL+'flash/autoviewer.swf', 'fullscreen_gallery', '100%', '100%', fv, {base:POKE.settings.MEDIA_URL, bgcolor: "#000000"}, {});
		},
		on_close : function () {
			POKE.hash.go('index');
		},
		revert_to_html : function () {
			$('#'+settings.element_id).show();
			$('body').removeClass('full').find('#fullscreen_gallery').remove();
		}
	};
}();


POKE.decorators = {
	scope : function (fn, obj) {
		var wrapper = function() {
			return fn.apply(obj);
		};
		return wrapper;
	}
};

// 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;
};


POKE.slide = function () {
    var opts = {axis:'y', easing:'easeOutQuart'};
    var speed = 500;
    var amount = 150;
    return {
        down : function () {
            POKE.slide.go('+='+amount+'px', speed, opts);
            return false;
    	},
    	up : function () {
    	    POKE.slide.go('-='+amount+'px', speed, opts);
    	    return false;
    	},
    	go : function (where, speed, opts) {
    	    return $('#column-right .slide').scrollTo(where, speed, opts);
    	}
    };
}();

/**
 * Randomly reorder child elements.
 * The optional *callback* is called with each child and its new (deep) clone, allowing you to
 * copy data over or anything else you may require.
 *
 * Example usage:
 *  controls.songs.reorder(function(child, clone) {
 *    clone.data('info', child.data('info'));
 *    var id = child.data('info').id;
 *    if (self.current != undefined && self.current.data('info').id == id) self.current = clone;
 *    if (self.next != undefined    && self.next.data('info').id == id)    self.next = clone;
 *  });
 *
 * @see http://blog.rebeccamurphey.com/2007/12/11/jquery-plugin-randomly-reorder-children-elements/
 */
$.fn.reorder = function(callback) {
 
  // random array sort @see http://javascript.about.com/library/blsort2.htm
  function randOrd() { return(Math.round(Math.random())-0.5); }
 
  return($(this).each(function() {
    var $this = $(this);
    var $children = $this.children();
    var childCount = $children.length;
 
    if (childCount > 1) {
      $children.hide();
 
      var indices = new Array();
      for (i=0;i<childCount;i++) { indices[indices.length] = i; }
      indices = indices.sort(randOrd);
      $.each(indices,function(j,k) { 
        var $child = $children.eq(k);
        var $clone = $child.clone(true);
        $clone.show().appendTo($this);
        if (callback != undefined) {
          callback($child, $clone);
        }
        $child.remove();
      });
    }
  }));
};