(function($){
	
	//STRING METHODS
	String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,''); };
	String.prototype.normalize = String.prototype.normalise = function() { return this.trim().replace(/\s+/g,' '); };
	String.prototype.startsWith = function(str,i){ i=(i)?'i':'';var re=new RegExp('^'+str,i);return (this.normalize().match(re)) ? true : false ; };
	String.prototype.endsWith = function(str,i){ i=(i)?'gi':'g';var re=new RegExp(str+'$',i);return (this.normalize().match(re)) ? true : false ; };
	
	$.extend({
		log : function(message,type,parameters){			
			try {
				switch(type){
					case 'log' : {
						console.log(message);
						break;	
					}	
					case 'debug' : {
						console.debug(message);	
						break;
					}
					case 'info' : {
						console.info(message);
						break;	
					}
					case 'warn' : {
						console.warn(message);	
						break;
					}
					case 'error' : {
						console.error(message);	
						break;
					}
					default : {
						console.log(message);
						break;
					}					
					
				}
			} catch(e) {
				//DO NOTHING	
			}			
		},
		
		isset : function(variable){
			return variable != undefined
		},
    	
		hasValue : function(variable){
			return $.isset(variable) && variable!=''
		},
		
    	exists : function(element) {
			return element != "" || $(element).length > 0			
		},
		
		parameterize : function(object,insideobject){
			var output = "";					
			if(insideobject){
				for(key in object){					
					if(typeof(object[key]) == "object" && !$.isArray(object[key])){			
						output += (output == "" ? "" : ",") + "\""+key+"\":{"+ $.parameterize(object[key],true) +"}";				
					} else if($.isArray(object[key])){		
						if(object[key].length == 0)
							output += (output == "" ? "" : ",") + "\""+key+"\":[]";
						else
							output += (output == "" ? "" : ",") + "\""+key+"\":\""+object[key]+"\"";													
					} else {
							output += (output == "" ? "" : ",") + "\""+key+"\":\""+object[key]+"\"";
					}
				}
				
			} else {								
				for(key in object){
					if(typeof(object[key]) == "object" && !jQuery.isArray(object[key])){						
						output += "&"+key+"={"+ $.parameterize(object[key],true) +"}";				
					} else if($.isArray(object[key])){						
						if(object[key].length == 0)
							output += "&"+key+"=[]";
						else
							output += "&"+key+"="+object[key];
					} else {
						if(output == "")
							output += "&"+key+"="+object[key];
						else
							output += "&"+key+"="+object[key];					
					}        
				}
			}			
			return output;
		},
			
    	highlight : function(haystack,needle){					
        	var regex = new RegExp(">([^<]*)?("+needle+")([^>]*)?<","ig");
        	return haystack.replace(regex,'>$1<span class="netblast-highlight">$2</span>$3<');
    	}
	});
	
	$.fn.extend({
		busy : function(parameters){
			var options = {
				background : '#ffffff',
				indicator : 'http://templates.strong.no/Webdesk/bilde/196649.gif'	// [string]   language code (e.g no, en, de)
			};	
			
			if(parameters) $.extend(options, parameters);    		
		
			return this.each(function(){ 
				var self = this;
				
				var position = $(self).position();
	
				var mask = $("<div></div>")
					.addClass("netblast-element-loader")
					.css({
						'background-color':options.background,
						'background-image': 'url('+options.indicator+')',
						'height':'60px',
						'display':'block',
						'z-index':'700',
						'background-repeat':'no-repeat',
						'background-position':'50% 50%'
						});
				$(self).hide().before($(mask));			
			});
		},
		
		finished : function(){
			return this.each(function(){
			   var self = $(this);
			   $(self).parent().find(".netblast-element-loader").fadeOut('fast');	
			   $(self).hide().slideDown(200).fadeIn(300);					  
			});	
		}					
	});
	
	
	jQuery.fn.fadeIn = function(speed, callback) { 
		return this.animate({opacity: 'show'}, speed, function() { 
			if (jQuery.browser.msie) 
				this.style.removeAttribute('filter');  
			if (jQuery.isFunction(callback)) 
				callback();  
		}); 
	}; 
	 
	jQuery.fn.fadeOut = function(speed, callback) { 
		return this.animate({opacity: 'hide'}, speed, function() { 
			if (jQuery.browser.msie)  
				this.style.removeAttribute('filter');  
			if (jQuery.isFunction(callback)) 
				callback();  
		}); 
	}; 
	 
	jQuery.fn.fadeTo = function(speed,to,callback) { 
		return this.animate({opacity: to}, speed, function() { 
			if (to == 1 && jQuery.browser.msie)  
				this.style.removeAttribute('filter');  
			if (jQuery.isFunction(callback)) 
				callback();  
		}); 
	}; 
	
	//RSS FEED - ADDED 29th of July 2011	
	function rss(element, feed){
    	try {    
        	jQuery.get('/Webdesk/rss?source='+feed+'&encoding=iso', function(d) {
            	var html = '<ul class="link-list">';
	            jQuery(d).find('item').each(function(index,el) {
	                if(index == 5) return false;
	                var $item = jQuery(this);
	                var title = $item.find('title').text();
	                var link = $item.find('link').text();
	                var description = $item.find('description').text();
	                var pubDate = $item.find('pubDate').text();
	                html += "<li><a href=\"" + link + "\" target=\"_blank\">" + title + "<\/a><\/li>"; 
	            });
	            jQuery(element).append(html+"<\/ul>");
	        });
	    } catch(e){
	        //console.log(e);
	    }
	}
	
})(jQuery);



/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.metadata.js 3640 2007-10-11 18:34:38Z pmclanahan $
 *
 */

/**
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are four supported types of metadata storage:
 *
 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *          
 *   class: Inside the class attribute, wrapped in curly braces: { }
 *   
 *   elem:  Inside a child element (e.g. a script tag). The
 *          name parameter indicates *which* element.
 *   html5: Values are stored in data-* attributes.
 *          
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 * 
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 * 
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 * 
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 * 
 * @example <p id="one" class="some_class" data-item_id="1" data-item_label="Label">This is a p</p>
 * @before $.metadata.setType("html5")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a series of data-* attributes
 *
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

(function($) {

$.extend({
  metadata : {
    defaults : {
      type: 'class',
      name: 'metadata',
      cre: /({.*})/,
      single: 'metadata'
    },
    setType: function( type, name ){
      this.defaults.type = type;
      this.defaults.name = name;
    },
    get: function( elem, opts ){
      var settings = $.extend({},this.defaults,opts);
      // check for empty string in single property
      if ( !settings.single.length ) settings.single = 'metadata';
      
      var data = $.data(elem, settings.single);
      // returned cached data if it already exists
      if ( data ) return data;
      
      data = "{}";
      
      var getData = function(data) {
        if(typeof data != "string") return data;
        
        if( data.indexOf('{') < 0 ) {
          data = eval("(" + data + ")");
        }
      }
      
      var getObject = function(data) {
        if(typeof data != "string") return data;
        
        data = eval("(" + data + ")");
        return data;
      }
      
      if ( settings.type == "html5" ) {
        var object = {};
        $( elem.attributes ).each(function() {
          var name = this.nodeName;
          if(name.match(/^data-/)) name = name.replace(/^data-/, '');
          else return true;
          object[name] = getObject(this.nodeValue);
        });
      } else {
        if ( settings.type == "class" ) {
          var m = settings.cre.exec( elem.className );
          if ( m )
            data = m[1];
        } else if ( settings.type == "elem" ) {
          if( !elem.getElementsByTagName ) return;
          var e = elem.getElementsByTagName(settings.name);
          if ( e.length )
            data = $.trim(e[0].innerHTML);
        } else if ( elem.getAttribute != undefined ) {
          var attr = elem.getAttribute( settings.name );
          if ( attr )
            data = attr;
        }
        object = getObject(data.indexOf("{") < 0 ? "{" + data + "}" : data);
      }
      
      $.data( elem, settings.single, object );
      return object;
    }
  }
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 *
 * @name metadata
 * @descr Returns element's metadata object
 * @param Object opts An object contianing settings to override the defaults
 * @type jQuery
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
  return $.metadata.get( this[0], opts );
};

})(jQuery);
