/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */
(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);


/*
 * jQuery Form Default - by jason palmer
 * http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/
 */
jQuery.fn.DefaultValue = function(text){
    return this.each(function(){	
		//Make sure we're dealing with text-based form fields
		if($(this).attr('type') != 'text' && $(this).attr('type') != 'password' && $(this).attr('type') != 'textarea')
			return;
		
		//Store field reference
		var fld_current = this;		
		
		//Set value initially if none are specified
        if(this.value == '' || this.value == text) {
			this.value = text;
		} else {
			//Other value exists - ignore
			$(this).addClass('ui_inputtext_focus');
			return;
		}
		
		//Remove values on focus
		$(this).focus(function() {
			$(this).addClass('ui_inputtext_focus');
			if(this.value==text || this.value=='') {
				this.value='';	
			}
		});
		
		//Place values back on blur
		$(this).blur(function() {
			$(this).removeClass('ui_inputtext_focus');
			if(this.value==text || this.value=='') {
				this.value=text;
			} else {
				$(this).addClass('ui_inputtext_focus');
			}
		});
		
		//Capture parent form submission
		//Remove field values that are still default
		$(this).parents("form").each(function() {
			//Bind parent form submit
			$(this).submit(function() {
				if(fld_current.value==text) {
					fld_current.value='';
				}
			});
		});
    });
};
	
jQuery.fn.FirstCapital = function(){
    return this.each(function() {	
		var $this = $(this);
		
		//Make sure we're dealing with text-based form fields
		if($this.attr('type') != 'text')
			return;
			
		function formatText(str) {
			return str.toLowerCase().replace(/\b[a-z]/g, cnvrt);
			function cnvrt() {
				return arguments[0].toUpperCase();
			}
		}

		$this.keyup(function (e) {
			$this.val(formatText($this.val()));
		});
    });
};

		
function formatCurrency(num) {
	num = num.toString().replace(/\$|\./g,'');
	
	if(isNaN(num))
		num = "";
		
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return num;
}

jQuery.fn.Currency = function(){
    return this.each(function() {	
		var $this = $(this);
		
		//Make sure we're dealing with text-based form fields
		if($this.attr('type') != 'text')
			return;

		$this.keyup(function (e) {
			$this.val(formatCurrency($this.val()));
		});
    });
};
 
jQuery.fn.Highlight = function() {
	return this.each(function() {
		var $this = $(this);
		var bgcolor = $this.css('background');
		
		$this.animate({background: '#fff600'},1500).animate({background: bgcolor},1500);
    });
};

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

jQuery.fn.jGMaps = function(lng,lat,zoom) {
	return this.each(function() {
	
		try {
			var testing = google;
		} catch (e) {
			return false;
		}
		
    	var myLatlng = new google.maps.LatLng(lat, lng);
		var myOptions = {
		  zoom: zoom,
		  center: myLatlng,   
		  mapTypeControl: false,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(this, myOptions);

		var marker = new google.maps.Marker({
			position: myLatlng,
			map: map,
			title:"Longitude: " + lng + ", Latitude: " + lat
		}); 
    });
};

jQuery.fn.jGEditableMaps = function(lng,lat,zoom) {
	return this.each(function() {
	
		try {
			var testing = google;
		} catch (e) {
			return false;
		}
		
		var myLatlng;
		
		if (typeof(lng) == 'object')
			myLatlng = lng;
		else 
			myLatlng = new google.maps.LatLng(lat, lng);
			
		var myzoom = (zoom == undefined ? ((typeof(lng) == 'object') ? lat : 15) : zoom);
		var myOptions = {
		  zoom: myzoom,
		  center: myLatlng,   
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(this, myOptions);
		
		var marker = new google.maps.Marker({
			position: myLatlng,
			map: map,
			title:"Longitude: " + lng + ", Latitude: " + lat,
			draggable:true
		});
		
		if (marker.position != null) {
			$('body').data('map',{
				zoom: map.getZoom(),
				lng:marker.position.lng() + '',
				lat:marker.position.lat() + ''
			});    
				
			google.maps.event.addListener(map, 'zoom_changed', function() {
				$('body').data('map',{
					zoom:map.getZoom(),
					lng:marker.position.lng() + '',
					lat:marker.position.lat() + ''
				});    
			});	
			google.maps.event.addListener(marker, 'dragend', function() {
				$('body').data('map',{
					zoom: map.getZoom(),
					lng:marker.position.lng() + '',
					lat:marker.position.lat() + ''
				}); 
				
				marker.setTitle("Longitude: " + marker.position.lng() 
								+ ", Latitude: " + marker.position.lat());
				
			});	
		}
    });
};

/**
 * addConfrim , By M. Rizky Ramadhan
 * add confirmation dialog box (usually for deleting something)
 */

(function($) {   
	$.fn.addConfirm = function(options) {
		var defaults = {
			title:null,
			text:null,
			yesText:"Setuju",
			noText:"Tidak Setuju",
			width:300,
			left:0,
			top:0,
			noAnimation:false,
			setAbsolute:false,
			placement:"after", //after,before,prepend,append
			afterDraw:null,
			onAccept:null,
			onReject:null
		};
		
		var options = $.extend(defaults, options);
		var $this = $(this);
		
		var d = new Date();
		var timestamp = d.getTime();
		var absolute = (options.setAbsolute ? "position:absolute;" : "position:relative;");
		
		$inserted = $('<div id="conf_' + timestamp + '" class="confirm_box" style="z-index:99999999;' + absolute + 'width:' + options.width + 'px;margin:' + options.top + 'px 0px 0px ' + options.left + 'px"><div class="profile_section_header_add" style="background:#ECEBEB;padding-left:10px;width:' + (options.width * 1 - 15) + 'px"><a href="#conf_' + timestamp + '" class="close_sub"></a>' + options.title + '</div><div class="profile_section_content_sub"  style="width:' + (options.width * 1 - 10) + 'px;padding:5px !important;"><div class="add_content"  style="width:' + (options.width * 1 - 16) + 'px;padding:0px !important;"><div class="add_box"  style="font-weight:bold;text-align:center;width:' + (options.width * 1 - 30) + 'px;padding:10px 10px 8px 10px;"><div style="margin-bottom:10px;">' + options.text + '</div><div style="height:8px;border-top:1px dashed #999"></div><a href="#conf_' + timestamp + '" class="confirm_yes boxed_link" style="text-decoration:none;font-size:11px;">' + options.yesText + '</a>&nbsp; &nbsp; <a href="#conf_' + timestamp + '" class="confirm_no boxed_link" style="text-decoration:none;font-size:11px;">' + options.noText + '</a></div></div></div></div>');
		
		function press(el) {
			$(el).attr('style','text-decoration:none;font-size:11px;background:#d5d5d5;');
		}
		
		function unpress(el) {
			$(el).attr('style','text-decoration:none;font-size:11px;');
		}
		
		function remove_confirm(instant) {		
			$inserted.find(".profile_section_header_add").hide();
			
			if (!instant) {
				$inserted.find(".profile_section_content_sub").fadeOut('fast',function() {
					$inserted.remove();
				});
			} else {
				$inserted.find(".profile_section_content_sub").hide();
				$inserted.remove();
			}
		}
		
		$inserted.find('.close_sub,.confirm_no').click(function() {
			if (options.onReject != null) {
				options.onReject();
			}
			remove_confirm(true);
		});
		
		$inserted.find('.confirm_no').hover(
		function() { press(this); },
		function() { unpress(this); });
		
		$inserted.find('.confirm_yes').click(function() {
			if (options.onAccept != null) {
				options.onAccept();
			}
			remove_confirm(true);
		})
		.hover(
		function() { press(this); },
		function() { unpress(this); });
		
		switch (options.placement) {
			case "after":$inserted.insertAfter($this);break;
			case "before":$inserted.insertBefore($this);break;
			case "prepend":$inserted.prependTo($this);break;
			case "append":$inserted.appendTo($this);break;
		}
		$inserted.find(".profile_section_header_add").show();
		
		if (!options.noAnimation)
			$inserted.find(".profile_section_content_sub").slideDown('fast');
		else 
			$inserted.find(".profile_section_content_sub").show();
		
		if (options.afterDraw != null) {
			options.afterDraw();
		}
	}
})(jQuery);	


/**
 * addPopup , By M. Rizky Ramadhan
 * add pop up for explaining something 
 */

(function($) {   
	$.fn.addPopup = function(options) {
		var defaults = {
			text:"",
			width:"auto",
			height:"auto",
			left:0,
			top:0,
			arrowMargin:10,
			setAbsolute:true,
			arrowPosition:"top", //top,bottom,left,right
			placement:"after", //after,before,prepend,append,
			effect:"none", //none,slide,fade
			effectOptions:"both", //both,in-only,out-only
			afterDraw:null
		};
		
		var options = $.extend(defaults, options);
		var $this = $(this);
		
		var width = (isNaN(options.width) ? "auto" : options.width + "px");
		var height = (isNaN(options.height) ? "auto" : options.height + "px");
		var margin = 'style="margin-left:' + options.arrowMargin + 'px";';
		var absolute = (options.setAbsolute ? "position:absolute;" : "position:relative;");
		
		$('.popup').remove();
		
		switch (options.arrowPosition) {
			case "left":margin = 'style="margin-top:' + options.arrowMargin + 'px";';break;
			case "right":margin = 'style="margin-top:' + options.arrowMargin + 'px";';break;
			case "bottom":margin = 'style="margin-left:' + options.arrowMargin + 'px";';break;
		}
		
		$inserted = $('<div class="popup" style="' + absolute + ';margin:' + options.top + 'px 0px 0px ' + options.left + 'px;" ><div class="popup_content" style="width:' + width + ';height:' + height +'">' + options.text + '</div></div>');
		$arrow = $('<div class="popup_arrow_' + options.arrowPosition + '" ' + margin + '></span></div>');
		
		if (options.arrowPosition == "bottom")
			$arrow.appendTo($inserted);
		else 
			$arrow.prependTo($inserted);
		
		if ($this.next().hasClass("popup")) $this.next().remove();
		if ($this.prev().hasClass("popup")) $this.prev().remove();
		$this.find(".popup").remove();
		
		switch (options.placement) {
			case "after":$inserted.insertAfter($this);break;
			case "before":$inserted.insertBefore($this);break;
			case "prepend":$inserted.prependTo($this);break;
			case "append":$inserted.appendTo($this);break;
		}
		
		if (options.effect == "fade") {
			if (options.effectOptions != "out-only")
			$inserted.hide().fadeIn();
			if (options.effectOptions != "in-only")
			setTimeout(function() { $inserted.fadeOut() },5000);
		} 
		else if (options.effect == "slide") {
			if (options.effectOptions != "out-only")
			$inserted.hide().slideDown();
			if (options.effectOptions != "in-only")
			setTimeout(function() { $inserted.slideUp() },5000);
		}
		
		if (options.afterDraw != null) options.afterDraw($inserted);
		
	}
})(jQuery);	


/**
 * send , By M. Rizky Ramadhan
 * ajax data send with loading and error notification 
 */
 
function send(options) {
	var defaults = {
		url:"",
		data:function() {},
		response:function(data) {},
		startsend:function() {},
		loading_el:null,
		error_el:null
	};
	
	var o = $.extend(defaults, options);
	var $this = $(this);
		
	if (o.loading_el != null) {
		o.loading_el.show();
	}
	
	if (o.error_el != null) {
		o.error_el.hide();
	}
	
	var submit = o.startsend();
	if (submit == false) {
		o.loading_el.hide();
		return false;
	}
	
	var requestdata = o.data();
	
	$.post(o.url,requestdata,function(rdata) {
		if (o.loading_el != null) {
			o.loading_el.hide();
		}
		
		o.response(rdata);
		
		if (o.error_el != null) {
			if (rdata.success == false) {
				o.error_el.show();
				$errorul = o.error_el.find('ul');
				$errorul.empty();
				$.each(rdata.error,function() {
					$errorul.append('<li>' + this + '</li>');
				});
			}
		}
	},"json");	
}

(function($) {   
	$.fn.send = function(options) {
		var defaults = {
			url:"",
			data:function($this) {},
			response:function(data,$this) {},
			startsend:function($this) {},
			loading_el:null,
			error_el:null
		};
		
		var o = $.extend(defaults, options);
		var $this = $(this);
	
		$this.each(function() {	
			$(this).submit(function() {
				if (o.loading_el != null) {
					o.loading_el.show();
				}
				
				if (o.error_el != null) {
					o.error_el.hide();
				}
				
				var submit = o.startsend($(this));
				if (submit == false) {
					o.loading_el.hide();
					return false;
				}
			
				var $this = $(this)
				$.post(o.url,o.data($(this)),function(rdata) {
					if (o.loading_el != null) {
						o.loading_el.hide();
					}
					
					o.response(rdata,$this);
					
					if (o.error_el != null) {
						if (rdata.success == false) {
							o.error_el.show();
							$errorul = o.error_el.find('ul');
							$errorul.empty();
							$.each(rdata.error,function() {
								$errorul.append('<li>' + this + '</li>');
							});
						}
					}
				},"json");
				
				return false;
			});
		});
	}
})(jQuery);	

