
// jQuery Plugins //////////////////////////////////////////////////////////////////////////

// Mouse wheel Plugin ////////////////////////////////////////////////////////
(function($) {
$.fn.extend({
	mousewheel: function(f) {
		if (!f.guid) f.guid = $.event.guid++;
		if (!$.event._mwCache) $.event._mwCache = [];
		
		return this.each( function() {
			if (this._mwHandlers) return this._mwHandlers.push(f);
			else this._mwHandlers = [];
			
			this._mwHandlers.push(f);
			
			var s = this;
			
			this._mwHandler = function(e) {
				e = $.event.fix(e || window.event);
				var delta = 0, returnValue = true;
				
				if (e.wheelDelta)  delta = e.wheelDelta/120;
				if (e.detail)      delta = -e.detail/3;
				if (window.opera)  delta = -e.wheelDelta;
				
				for (var i=0; i<s._mwHandlers.length; i++)
					if (s._mwHandlers[i])
						if ( s._mwHandlers[i].call(s, e, delta) === false ) {
							returnValue = false;
							e.preventDefault();
							e.stopPropagation();
						}
				
				return returnValue;
			};
			
			if (this.addEventListener)
				if ($.browser.mozilla) this.addEventListener('DOMMouseScroll', this._mwHandler, false);
				else                   this.addEventListener('mousewheel',     this._mwHandler, false);
			else
				$.event.add(this, 'mousewheel', this._mwHandler);
			
			$.event._mwCache.push( $(this) );
		});
	},
	
	unmousewheel: function(f) {
		return this.each( function() {
			if ( f && this._mwHandlers ) {
				for (var i=0; i<this._mwHandlers.length; i++)
					if (this._mwHandlers[i] && this._mwHandlers[i].guid == f.guid)
						delete this._mwHandlers[i];
			} else {
				if (this.addEventListener)
					if ($.browser.mozilla) this.removeEventListener('DOMMouseScroll', this._mwHandler, false);
					else                   this.removeEventListener('mousewheel',     this._mwHandler, false);
				else
					$.event.remove(this, 'mousewheel', this._mwHandler);
					
				this._mwHandlers = this._mwHandler = null;
			}
		});
	}
});
// clean-up
$(window).bind('unload', function() {
    var els = $.event._mwCache || [];
	for (var i=0; i<els.length; i++)
	    els[i].unmousewheel();
});
	
// Query String Plugin ////////////////////////////////////////////////////////
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 ? "#" : "?" : "";
  
  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 = /^(\S+?)(\[\S*\])?$/.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 = this.split('=')[0];
            var val = this.split('=')[1];
            
            if (!key) return;
            
            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 = decodeURIComponent(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, force_array) {
        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()];
        }
        if (force_array)
            return target ? $.makeArray(target) : []
        return 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;
      },
      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 addFields = function(arr, key, value) {
          if (!is(value) || value === false) return;
          var o = [key];
          if (value !== true) {
            o.push("=");
            o.push(encodeURIComponent(value));
          }
          arr.push(o.join(""));
        };
        var build = function(obj, base) {
          var newKey = function(key) {
            return !base || base == "" ? [key].join("") : [base].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


// Custom Query String Plugin ////////////////////////////////////////////////////////
jQuery.parseQstr = function( str ) {
    var q = {};
    var match = str.match(/([^?#]*)(#.*)?$/);
    if (!match) return {};
    str = match[0];
    var p = str.split(/[&;]/);
    for (var i=0; i<p.length; i++) {
        var n = p[i].split('=');
        var k = decodeURIComponent(n[0]);
        if (n.length == 2) var v = decodeURIComponent(n[1]);
        else var v = k;
        if (typeof q[k] == 'undefined') q[k] = v;
        else {
            var a = eval(q[k]);
            a.push(v);
            q[k] = a;
        }
    }
    return q;
}

jQuery.objToQstr = function ( obj ) {
    var str = '';
    $.each( obj, function(key, val) {
        str+= encodeURIComponent(key)+'='+encodeURIComponent(val) + '&';
    });
    return str.replace(/&$/,'');
}

// Centering Plugin ////////////////////////////////////////////////////////
jQuery.fn.vcenter = function() {
    return this.each( function() {
        var $obj = $(this);
        var $p = $obj.parent();
        
        var t = parseInt( ($p.height() - $obj.height()) / 2 );
        if( $obj.css('position').toLowerCase() == 'absolute' ) {
            $obj.css('top', t+'px');
        }
        else {
            $obj.css('marginTop', t+'px');
        }
        
    });
}

jQuery.fn.center = function() {
    return this.each( function() {
        var $obj = $(this);
        var $p = $obj.parent();
        
        var l = parseInt( ($p.width() - $obj.width()) / 2 );
        if( $obj.css('position').toLowerCase() == 'absolute' ) {
            $obj.css('left', l+'px');
        }
        else {
            $obj.css('margin-left', l+'px');
        }
        
    });
}


// Color Formatting Plugin//////////////////////////////////////////////////////////
// Takes color in hexadecimal notation and returns [r, g, b] 
jQuery.hex2rgb = function(color) {
    var rgb;
    color = color.replace(/^#/,'');
    if( color.length == 6 ) {
        rgb = [
            parseInt(color.substring(0,2), 16),
            parseInt(color.substring(2,4), 16), 
            parseInt(color.substring(4,6), 16)
        ];
    }
    else if( color.length == 3 ) {
        rgb = [
            parseInt(color.substring(0,1), 16),
            parseInt(color.substring(1,2), 16), 
            parseInt(color.substring(2,3), 16)
        ];
    } else {
        rgb = [0,0,0];
    }
    return rgb;
}
// Takes r, g, b and returns the hexadecimal version of a color
jQuery.rgb2html = function(R,G,B) {return $.toHex(R) + $.toHex(G) + $.toHex(B)}

// Converts a decimal number to hexadecimal
jQuery.toHex = function(N) {
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16)
      + "0123456789ABCDEF".charAt(N%16);
}

// Takes a color string returned by the browser and parses it into a hexadecimal color string
jQuery.colorFormat = function(color) {
    if( !color ) return;
    color = color.replace('#','');
    var returnColour = "";
    if(color != "transparent") {
        if(color.substr(0, 3) == "rgb") {
            var a = color.replace(/[^0-9|,]/g,'').split(',');
            returnColour = $.rgb2html(a[0],a[1],a[2]);            
        }        
        else if(color.length == 3) {            
            returnColour = color.substring(0, 1) + 
                    color.substring(0, 1) + 
                    color.substring(1, 2) +
                    color.substring(1, 2) +
                    color.substring(2, 3) + 
                    color.substring(2, 3);
        }        
        else {
            returnColour = color;            
        }        
    }
    else if( color == "transparent" ) {
        returnColour = 'transparent';
    }    
    return returnColour;    
}

// Rollover Plugin //////////////////////////////////////////////////////////////////////////
jQuery.rollover = {
    _get_filter : function(obj) { // handle ie6 filter
        if (!$.browser.msie) return obj;
        filter = $(obj).css('filter');
        if( filter )  return obj.filters(0);
        else return obj;
    },
    over: function(e) {
        var obj = this;
        var img = obj;
        var prop = $.data(obj, 'rollover');
        if( img.tagName.toLowerCase() != 'img' ) img = $('img',obj)[0];        
        if( prop.saved_src ) return;
        img = $.rollover._get_filter(img);
        prop.saved_src = img.src;
        $.data(obj, 'rollover', prop);
        img.src = $.rollover.over_src(img.src);
    },
    textover : function(e) {
        var obj = this;
        var img = obj;
        var prop = $.data(obj, 'rollover');
        if( img.tagName.toLowerCase() != 'img' ) img = $('img',obj)[0];
        if( prop.saved_src ) return;
        img = $.rollover._get_filter(img);
        prop.saved_src = img.src;
        $.data(obj, 'rollover', prop);
        img.src = $.rollover.textover_src(img.src, prop.options);
    },
    over_src: function(src) {
        return src.replace(/\.(\w+)$/, "_over.$1");
    },
    textover_src: function(src, settings ){
        var baseURL = settings.baseURL;
        var filename = src.split('?')[0].split('/').slice(-1)[0];
        var params = {};
        $.each( settings, function(k,v) {
            if( k != 'baseURL' ) params[k] = v;
        });
        var q = $.parseQstr(src);
        $.extend(q,params);
        return baseURL + filename + '?' + $.param(q);
    },
    out : function(e) {
        var obj = this;
        var img = obj;
        var prop = $.data(obj, 'rollover');
        if( $(obj).is('.ignore') ) return;        
        if( img.tagName.toLowerCase() != 'img' ) img = $('img',obj)[0];        
        if( prop.saved_src ) $.rollover._get_filter(img).src = prop.saved_src;
        prop.saved_src = null;
        $.data(obj, 'rollover', prop);
    }    
};
jQuery.fn.rollover = function () {
    return this.each( function(i,obj) {
        $.data(obj, 'rollover', {saved_src: null});
        $(obj).unbind('mouseover', $.rollover.over).unbind('mouseout', $.rollover.out).
            mouseover($.rollover.over).mouseout($.rollover.out);        
        $(obj).preloadImg();
    });
};
jQuery.fn.textover = function (options) {
    var defaults = {
        baseURL: '/buttons/'
    }
    return this.each( function(i,obj) {
        options = $.extend({}, defaults, options || {});
        if( !options.color ) {
            var c = $(obj).addClass('hover').css('color') || '000000';
            $(obj).removeClass('hover');
            c = '#' + $.colorFormat(c);
            options.color = c;
        }
        $.data(obj, 'rollover', {
            saved_src: null,
            options: options
        });
        $(obj).unbind('mouseover', $.rollover.textover).unbind('mouseout', $.rollover.out).
            mouseover($.rollover.textover).mouseout($.rollover.out);
        $(obj).preloadImg();
    });
};
jQuery.fn.rolloverUnbind = function () {
    return this.each( function(i,obj) {
        $(obj).unbind('mouseover', $.rollover.over);
        $(obj).unbind('mouseover', $.rollover.textover);
        $(obj).unbind('mouseout', $.rollover.out);        
        $.removeData(obj, 'rollover');
    });
};

// Preloads rollover images according to rollover replacement rules
jQuery.fn.preloadImg = function () {
    return this.each( function() {
        if( typeof(this.rollover) == 'undefined' || !this.rollover ) return;
        var img = this;
        if( img.tagName.toLowerCase() != 'img' ) img = $('img',this)[0];
        var preloader = new Image();
        if( img.src.search('image.php') == -1 )
            preloader.src = $.rollover.over_src(img.src);
        else
            preloader.src = $.rollover.textover_src(img.src,this.rollover.settings);   

    });
};


// Image Replacement Plugin//////////////////////////////////////////////////////////

// Uses image generator to replace the element's text with an image
jQuery.fn.imageReplace = function (settings) {
    var settings = $.extend({},  settings);
    baseURL = '/buttons/';
    return this.each( function() {
        $obj = $(this);
        var text = $.trim($obj.text());
        if( text.length < 1 ) return;
        if( text == '&nbsp;') return;
       
        var options = $.extend({}, settings);
        if( !options.color ) options.color = '#' + ($.colorFormat($obj.css('color')|| '000000'));
        if( !options.size ) options.size = parseInt($obj.css('font-size'));
        if( $obj.css('text-transform') == 'uppercase' ) text = text.toUpperCase();
        else if( $obj.css('text-transform') == 'lowercase' ) text = text.toLowerCase();
        if( !options.align ) options.align = $obj.css('text-align');
        var option_string = '';
        $.each(options, function(key,val) {
            option_string += '&'+encodeURIComponent(key)+'='+encodeURIComponent(val);
        }); 
        option_string = option_string.replace(/^&/,'');
        uri_text = encodeURIComponent(text).replace('%2F', '%252F');
        $obj.empty().append('<img src="'+ baseURL + uri_text +'.png?' + option_string + '" alt="'+text+'">');
    });
}



// Generate 32 char random id 
function gen_id() {
    var id = ""
    for (var i=0; i < 32; i++) {
        id += Math.floor(Math.random() * 16).toString(16); 
    }
    return id
}

jQuery.fn.uploadProgress = function() {
    return this.each( function() {
        // Add upload progress for multipart forms.
        var $form = $(this);
        if (! ($form.is('form') && $form.attr('enctype') == 'multipart/form-data')) return;
                
        $form.submit(function(){ 
            // First make sure we're actually uploading something.
            var has_upload_data = false;
            var $inputs = $('input[@type=file]',this).each(function() {
                if (this.value) has_upload_data = true;
            });
            if (!has_upload_data) return true;

            // Prevent multiple submits
            if ($.data(this, 'submitted')) return false;

            var freq = 5000; // freqency of update in ms
            var id = gen_id(); // id for this upload so we can fetch progress info.
            var progress_url = admin_root + 'upload_progress/'; // ajax view serving progress info

            // Append X-Progress-ID id form action
            this.action += (this.action.indexOf('?') == -1 ? '?' : '&') + 'X-Progress-ID=' + id;
            
            var $progress = $('<div id="upload-progress" class="upload-progress"></div>').
                insertAfter($inputs.slice(0,1)).append('<div class="progress-container"><span class="progress-info">uploading 0%</span><div class="progress-bar"></div></div>');

            // progress bar position
            $progress.show();

            $form.trigger('form-upload');

            // Update progress bar
            function update_progress_info() {
                $progress.show();
                $.getJSON(progress_url, {'X-Progress-ID': id}, function(data, status){
                    if (data) {
                        var progress = parseInt(data.uploaded) / parseInt(data.length);
                        var width = $progress.find('.progress-container').width()
                        var progress_width = width * progress;
                        $progress.find('.progress-bar').width(progress_width);
                        $progress.find('.progress-info').text('uploading ' + parseInt(progress*100) + '%');
                    }
                    window.setTimeout(update_progress_info, freq);
                });
            };
            window.setTimeout(update_progress_info, freq);

            $.data(this, 'submitted', true); // mark form as submitted.
        });
    });
}

jQuery.fn.fullScreenImage = function() {
    var resize = function(obj) {
        var wh = $(window).height();
        var ww = $(window).width();
        var $$= $(obj);
        $$.css({
            position: 'absolute'
        });
        var h = $$.height();
        var w = $$.width();
        var width_ratio = ww / w;
        var height_ratio = wh / h;
        if (width_ratio >= height_ratio) {
            $$.css({width: '100%', height: 'auto'});
        } else {
            $$.css({height: '100%', width: 'auto'});
        }
    }

    return this.each(function() {
        var obj = this;
        resize(obj);
        $(window).load(function(){ resize(obj)}).resize(function() {resize(obj)});
    });
}

})(jQuery);

