/*
 * This file is part of the Twist Framework package.
 * (c) 2007-2008 Simon Chollet <simon.chollet@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */


/*
 * Prepopulate fields
 */
(function($){

	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;
	    }
	};

	jQuery.setTwistUserData = function(index, data){ //stores data in a cookie
		var user_data_str = $.cookie("user_data");
		if(user_data_str != null && user_data_str != '')
			var user_data = $.evalJSON(user_data_str);
		else
			var user_data = {};

		if(user_data[index] == null)
			user_data[index] = {};
			
		user_data[index] = data;
		$.cookie("user_data", $.toJSON(user_data),{path:'/'});
	};

	jQuery.getTwistUserData = function(index){ //retrieves data from a cookie
		var user_data;
		var user_data_str = $.cookie("user_data");

		if(user_data_str != null && user_data_str != '')
			user_data = $.evalJSON(user_data_str);

		if(user_data != null && user_data[index] != null)
			return user_data[index];
		return null;
	};


	jQuery.htmlSpecialChars = function(str){
		str = str.replace(/&/g,"&amp;")
		str = str.replace(/\"/g,"&quot;")
		str = str.replace(/\'/g,"&#039;")
		str = str.replace(/</g,"&lt;")
		str = str.replace(/>/g,"&gt;")
		return str;
	};

	jQuery.nl2br = function(str){
		//replace(/([^>]?)\n/g, '$1<br>\n')
		return str.replace(/\n/g, '<br>');
	};

	jQuery.rgbToHex = function(rgb){
		if(typeof(rgb) == "string")
			rgb = rgb.substring(4,rgb.length - 1).split(', ');

		function toHex(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);
		}

		return "#"+(toHex(rgb[0])+toHex(rgb[1])+toHex(rgb[2])).toLowerCase();
	};

	jQuery.preloadImages = function(){
	  for(var i = 0; i<arguments.length; i++){
	    jQuery("<img>").attr("src", arguments[i]);
	  }
	};

	jQuery.fn.disableLink = function(){
		$(this).attr('href','#').unbind('click').click(function() {return false;});
	}

	jQuery.fn.prePopulate = function(str, text_color, empty_on_focus){
		var normal_color = $(this).css('color');
		$(this).data("normal_color", normal_color); //for destroy

		var val = $(this).val();
		var empty_on_focus = (empty_on_focus != null) ? empty_on_focus : true ;

		if( val == null || val == '' || val == str){
			$(this).val(str);
			if (text_color != null){
				$(this).css('color', text_color);
			}
		}

		$(this).focus(function(){
			if($(this).val() == str){
				if(empty_on_focus)
					$(this).val('');

				if (text_color != null)
					$(this).css('color', normal_color);
			}

		});

		$(this).blur(function(){
			if($(this).val() == null || $(this).val() == '' || $(this).val() == str){
				$(this).val(str);
				if (text_color != null)
					$(this).css('color', text_color);
			}
		});

		return this;
	};

	//This is not very clean, as it removes all focus and blur binded functions. To be improved!
	jQuery.fn.prePopulateDestroy = function(){
		$(this).each(function(){
			var color = $(this).data("normal_color");
			if(color)
				$(this).css('color', color);
		});
		$(this).unbind("focus");
		$(this).unbind("blur");
	};

	jQuery.fn.countChars = function(output, settings){

		settings = jQuery.extend({
			sms:			false,
			max:			0,
			block_at_max:	true
		}, settings);

		$(this).keyup(function(){count(this)});
		count(this);

		function count(elem){
			var length = 0;
			var op_length = 0;//length for output
			var value = $(elem).val();
			if(settings['sms'] == true && value != '')
			{
				for(i=0; i < value.length; i++)
				{
					if( value.charAt(i).match(/\^|{|}|\\|\[|~|\]|\|/) || value.charAt(i) == "\u20AC" )
						length += 2;
					else
						length++;
				}
			}
			else
				length = value.length;

			if(settings['max'] != 0){
				op_length = (settings['max'] - length >= 0) ? settings['max'] - length : 0;
				if(settings['block_at_max'] == true && length >= settings['max']){
					$(elem).val($(elem).val().substr(0, settings['max']));
				}
			}
			else
				op_length = length;
		
			$(output).html(String(op_length));
		};
	};
	
})(jQuery);


