/**
 * jQuery.query - Query String Modification and Creation for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/8/13
 *
 * @author Blair Mitchelmore
 * @version 2.1.7
 *
 **/
new function(settings) { 
  // Various Settings
  var $separator = settings.separator || '&';
  var $spaces = settings.spaces === false ? false : true;
  var $suffix = settings.suffix === false ? '' : '[]';
  var $prefix = settings.prefix === false ? false : true;
  var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
  var $numbers = settings.numbers === false ? false : true;
  
  jQuery.query = new function() {
    var is = function(o, t) {
      return o != undefined && o !== null && (!!t ? o.constructor == t : true);
    };
    var parse = function(path) {
      var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
      while (m = rx.exec(match[2])) tokens.push(m[1]);
      return [base, tokens];
    };
    var set = function(target, tokens, value) {
      var o, token = tokens.shift();
      if (typeof target != 'object') target = null;
      if (token === "") {
        if (!target) target = [];
        if (is(target, Array)) {
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        } else if (is(target, Object)) {
          var i = 0;
          while (target[i++] != null);
          target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
        } else {
          target = [];
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        }
      } else if (token && token.match(/^\s*[0-9]+\s*$/)) {
        var index = parseInt(token, 10);
        if (!target) target = [];
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else if (token) {
        var index = token.replace(/^\s*|\s*$/g, "");
        if (!target) target = {};
        if (is(target, Array)) {
          var temp = {};
          for (var i = 0; i < target.length; ++i) {
            temp[i] = target[i];
          }
          target = temp;
        }
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else {
        return value;
      }
      return target;
    };
    
    var queryObject = function(a) {
      var self = this;
      self.keys = {};
      
      if (a.queryObject) {
        jQuery.each(a.get(), function(key, val) {
          self.SET(key, val);
        });
      } else {
        jQuery.each(arguments, function() {
          var q = "" + this;
          q = q.replace(/^[?#]/,''); // remove any leading ? || #
          q = q.replace(/[;&]$/,''); // remove any trailing & || ;
          if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
          
          jQuery.each(q.split(/[&;]/), function(){
            var key = decodeURIComponent(this.split('=')[0] || "");
            var val = decodeURIComponent(this.split('=')[1] || "");
            
            if (!key) return;
            
            if ($numbers) {
              if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
                val = parseFloat(val);
              else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
                val = parseInt(val, 10);
            }
            
            val = (!val && val !== 0) ? true : val;
            
            if (val !== false && val !== true && typeof val != 'number')
              val = val;
            
            self.SET(key, val);
          });
        });
      }
      return self;
    };
    
    queryObject.prototype = {
      queryObject: true,
      has: function(key, type) {
        var value = this.get(key);
        return is(value, type);
      },
      GET: function(key) {
        if (!is(key)) return this.keys;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        while (target != null && tokens.length != 0) {
          target = target[tokens.shift()];
        }
        return typeof target == 'number' ? target : target || "";
      },
      get: function(key) {
        var target = this.GET(key);
        if (is(target, Object))
          return jQuery.extend(true, {}, target);
        else if (is(target, Array))
          return target.slice(0);
        return target;
      },
      SET: function(key, val) {
        var value = !is(val) ? null : val;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        this.keys[base] = set(target, tokens.slice(0), value);
        return this;
      },
      set: function(key, val) {
        return this.copy().SET(key, val);
      },
      REMOVE: function(key) {
        return this.SET(key, null).COMPACT();
      },
      remove: function(key) {
        return this.copy().REMOVE(key);
      },
      EMPTY: function() {
        var self = this;
        jQuery.each(self.keys, function(key, value) {
          delete self.keys[key];
        });
        return self;
      },
      load: function(url) {
        var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
        var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
        return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
      },
      empty: function() {
        return this.copy().EMPTY();
      },
      copy: function() {
        return new queryObject(this);
      },
      COMPACT: function() {
        function build(orig) {
          var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
          if (typeof orig == 'object') {
            function add(o, key, value) {
              if (is(o, Array))
                o.push(value);
              else
                o[key] = value;
            }
            jQuery.each(orig, function(key, value) {
              if (!is(value)) return true;
              add(obj, key, build(value));
            });
          }
          return obj;
        }
        this.keys = build(this.keys);
        return this;
      },
      compact: function() {
        return this.copy().COMPACT();
      },
      toString: function() {
        var i = 0, queryString = [], chunks = [], self = this;
        var encode = function(str) {
          str = str + "";
          if ($spaces) str = str.replace(/ /g, "+");
          return encodeURIComponent(str);
        };
        var addFields = function(arr, key, value) {
          if (!is(value) || value === false) return;
          var o = [encode(key)];
          if (value !== true) {
            o.push("=");
            o.push(encode(value));
          }
          arr.push(o.join(""));
        };
        var build = function(obj, base) {
          var newKey = function(key) {
            return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
          };
          jQuery.each(obj, function(key, value) {
            if (typeof value == 'object') 
              build(value, newKey(key));
            else
              addFields(chunks, newKey(key), value);
          });
        };
        
        build(this.keys);
        
        if (chunks.length > 0) queryString.push($hash);
        queryString.push(chunks.join($separator));
        
        return queryString.join("");
      }
    };
    
    return new queryObject(location.search, location.hash);
  };
}(jQuery.query || {}); // Pass in jQuery.query as settings object

/*
	Picked up this script from: http://www.quirksmode.org/js/detect.html.
	Date: August 18, 2009.
*/
var BrowserDetect = {
	init: function() {
		this.browser = this.searchString(this.dataBrowser) || 'An unknown browser';
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| 'an unknown version';
		this.OS = this.searchString(this.dataOS) || 'an unknown OS';
	},
	searchString: function(data) {
		for (var i = 0; i < data.length; i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function(dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: 'Chrome',
			identity: 'Chrome'
		},
		{ 	string: navigator.userAgent,
			subString: 'OmniWeb',
			versionSearch: 'OmniWeb/',
			identity: 'OmniWeb'
		},
		{
			string: navigator.vendor,
			subString: 'Apple',
			identity: 'Safari',
			versionSearch: 'Version'
		},
		{
			prop: window.opera,
			identity: 'Opera'
		},
		{
			string: navigator.vendor,
			subString: 'iCab',
			identity: 'iCab'
		},
		{
			string: navigator.vendor,
			subString: 'KDE',
			identity: 'Konqueror'
		},
		{
			string: navigator.userAgent,
			subString: 'Firefox',
			identity: 'Firefox'
		},
		{
			string: navigator.vendor,
			subString: 'Camino',
			identity: 'Camino'
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: 'Netscape',
			identity: 'Netscape'
		},
		{
			string: navigator.userAgent,
			subString: 'MSIE',
			identity: 'Explorer',
			versionSearch: 'MSIE'
		},
		{
			string: navigator.userAgent,
			subString: 'Gecko',
			identity: 'Mozilla',
			versionSearch: 'rv'
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: 'Mozilla',
			identity: 'Netscape',
			versionSearch: 'Mozilla'
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: 'Win',
			identity: 'Windows'
		},
		{
			string: navigator.platform,
			subString: 'Mac',
			identity: 'Mac'
		},
		{
			   string: navigator.userAgent,
			   subString: 'iPhone',
			   identity: 'iPhone/iPod'
	    },
		{
			   string: navigator.userAgent,
			   subString: 'iPad',
			   identity: 'iPad'
	    },
		{
			string: navigator.platform,
			subString: 'Linux',
			identity: 'Linux'
		}
	]

};
BrowserDetect.init();

/*
 * 
 * jquery pagination
 * 
 */
//----------------------------------------------------------------------------
//Pagination Plugin - A jQuery Plugin to paginate content
//v 1.0 Beta
//Dual licensed under the MIT and GPL licenses.
//----------------------------------------------------------------------------
//Copyright (C) 2010 Rohit Singh Sengar
//http://rohitsengar.cueblocks.net/
//----------------------------------------------------------------------------
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
//----------------------------------------------------------------------------



;(function($){
/*******************************************************************************************/	
// jquery.pajinate.js - version 0.2
// A jQuery plugin for paginating through any number of DOM elements
// 
// Copyright (c) 2010, Wes Nolte (http://wesnolte.com)
// Liscensed under the MIT License (MIT-LICENSE.txt)
// http://www.opensource.org/licenses/mit-license.php
// Created: 2010-04-16 | Updated: 2010-04-26
/*******************************************************************************************/

	$.fn.pajinate = function(options){
		// Set some state information
		var current_page = 'current_page';
		var items_per_page = 'items_per_page';
		
		var meta;
	
		// Setup default option values
		var defaults = {
			item_container_id : '.content',
			items_per_page : 10,			
			nav_panel_id : '.page_navigation',
			num_page_links_to_display : 20,			
			start_page : 0,
			nav_label_first : 'First',
			nav_label_prev : 'Prev',
			nav_label_next : 'Next',
			nav_label_last : 'Last'
		};
		var options = $.extend(defaults,options);
		var $item_container;
		var $page_container;
		var $items;
		var $nav_panels;
	
		return this.each(function(){
			$page_container = $(this);
			$item_container = $(this).find(options.item_container_id);
			$items = $page_container.find(options.item_container_id).children();
			meta = $page_container;
			
			// Initialise meta data
			meta.data(current_page,0);
			meta.data(items_per_page, options.items_per_page);
					
			// Get the total number of items
			var total_items = $item_container.children().size();
		
			// Calculate the number of pages needed
			var number_of_pages = Math.ceil(total_items/options.items_per_page);
			
			// Construct the nav bar
			var more = '<span class="ellipse more">...</span>';
			var less = '<span class="ellipse less">...</span>';
			
			var navigation_html = '<a class="first_link" href="">'+ options.nav_label_first +'</a>';
			navigation_html += '<a class="previous_link" href="">'+ options.nav_label_prev +'</a>'+ less;
			var current_link = 0;
			while(number_of_pages > current_link){
				navigation_html += '<a class="page_link" href="" longdesc="' + current_link +'">'+ (current_link + 1) +'</a>';
				current_link++;
			}
			navigation_html += more + '<a class="next_link" href="">'+ options.nav_label_next +'</a>';
			navigation_html += '<a class="last_link" href="">'+ options.nav_label_last +'</a>';
			
			// And add it to the appropriate area of the DOM	
			$nav_panels = $page_container.find(options.nav_panel_id);			
			$nav_panels.html(navigation_html).each(function(){
			
				$(this).find('.page_link:first').addClass('first');
				$(this).find('.page_link:last').addClass('last');
				
			});
			
			// Hide the more/less indicators
			$nav_panels.children('.ellipse').hide();
			
			// Set the active page link styling
			$nav_panels.find('.previous_link').next().next().addClass('active_page');
			
			/* Setup Page Display */
			// And hide all pages
			$items.hide();
			// Show the first page			
			$items.slice(0, meta.data(items_per_page)).show();

			/* Setup Nav Menu Display */
			// Page number slices
			
			var total_page_no_links = $page_container.children(options.nav_panel_id+':first').children('.page_link').size();
			options.num_page_links_to_display = Math.min(options.num_page_links_to_display,total_page_no_links);

			$nav_panels.children('.page_link').hide(); // Hide all the page links
			
			// And only show the number we should be seeing
			$nav_panels.each(function(){
				$(this).children('.page_link').slice(0, options.num_page_links_to_display).show();			
			});
			
			/* Bind the actions to their respective links */
			 
			// Event handler for 'First' link
			$page_container.find('.first_link').click(function(e){
				e.preventDefault();
				
				movePageNumbersRight($(this),0);
				goto(0);				
			});			
			
			// Event handler for 'Last' link
			$page_container.find('.last_link').click(function(e){
				e.preventDefault();
				var lastPage = total_page_no_links - 1;
				movePageNumbersLeft($(this),lastPage);
				goto(lastPage);				
			});			
			
			// Event handler for 'Prev' link
			$page_container.find('.previous_link').click(function(e){
				e.preventDefault();
				showPrevPage($(this));
			});
			
			
			// Event handler for 'Next' link
			$page_container.find('.next_link').click(function(e){
				e.preventDefault();				
				showNextPage($(this));
			});
			
			// Event handler for each 'Page' link
			$page_container.find('.page_link').click(function(e){
				e.preventDefault();
				goto($(this).attr('longdesc'));
			});			
			
			// Goto the required page
			goto(parseInt(options.start_page));
			toggleMoreLess();
		});
		
		function showPrevPage(e){
			new_page = parseInt(meta.data(current_page)) - 1;						
			
			// Check that we aren't on a boundary link
			if($(e).siblings('.active_page').prev('.page_link').length==true){
				movePageNumbersRight(e,new_page);
				goto(new_page);
			}
				
		};
			
		function showNextPage(e){
			new_page = parseInt(meta.data(current_page)) + 1;
			
			// Check that we aren't on a boundary link
			if($(e).siblings('.active_page').next('.page_link').length==true){		
				movePageNumbersLeft(e,new_page);
				goto(new_page);
			}
				
		};
			
		function goto(page_num){
			
			var ipp = meta.data(items_per_page);
			
			var isLastPage = false;
			
			// Find the start of the next slice
			start_from = page_num * ipp;
			
			// Find the end of the next slice
			end_on = start_from + ipp;
			// Hide the current page	
			$items.hide()
					.slice(start_from, end_on)
					.show();
			
			// Reassign the active class
			$page_container.find(options.nav_panel_id).children('.page_link[longdesc=' + page_num +']').addClass('active_page')
													 .siblings('.active_page')
													 .removeClass('active_page');										 
			
			// Set the current page meta data							
			meta.data(current_page,page_num);
			
			// Hide the more and/or less indicators
			toggleMoreLess();
		};	
		
		// Methods to shift the diplayed index of page numbers to the left or right
		function movePageNumbersLeft(e, new_p){
			var new_page = new_p;
			
			var $current_active_link = $(e).siblings('.active_page');
		
			if($current_active_link.siblings('.page_link[longdesc=' + new_page +']').css('display') == 'none'){
				
				$nav_panels.each(function(){
							$(this).children('.page_link')
								.hide() // Hide all the page links
								.slice(parseInt(new_page - options.num_page_links_to_display + 1) , new_page + 1)
								.show();		
							});
			}
			
		} 
		
		function movePageNumbersRight(e, new_p){
			var new_page = new_p;
			
			var $current_active_link = $(e).siblings('.active_page');
			
			if($current_active_link.siblings('.page_link[longdesc=' + new_page +']').css('display') == 'none'){
												
				$nav_panels.each(function(){
							$(this).children('.page_link')
								.hide() // Hide all the page links
								.slice( new_page , new_page + parseInt(options.num_page_links_to_display))
								.show();
							});
			}
		}
		
		// Show or remove the ellipses that indicate that more page numbers exist in the page index than are currently shown
		function toggleMoreLess(){
													 
			if(!$nav_panels.children('.page_link:visible').hasClass('last')){					
				$nav_panels.children('.more').show();
			}else {
				$nav_panels.children('.more').hide();
			}
			
			if(!$nav_panels.children('.page_link:visible').hasClass('first')){
				$nav_panels.children('.less').show();
			}else {
				$nav_panels.children('.less').hide();
			}			
		}
		
	};
	
})(jQuery);
