/*
 * Author: aprian@mmcmg.com
 * JS Var: className = limitTextarea limit_[amount char allowed], e.g: limit_500 (limit 500 character)
 * CSS Var: .counter, .counterChar
 */

function limitTextarea() {
	
	var obj;
	$("textarea.limitTextarea").each( function(obj) {
		
		var elm = $(this);
		var obj = parseFloat(obj) + 1;
		
		var thisClass = $(this).attr('class').split(' ');
		var re = new RegExp('^(limit_)')
			for(i=0;i<thisClass.length;i++) {
				if(thisClass[i].match(re)) {
					limitSizes = thisClass[i].split('_');
					var maxChar = limitSizes[1];
				}
			}

		var leftChar = maxChar - elm.val().length;
		elm.after('<div class="counter">characters left: <span class="counterChar' + obj + '">' + leftChar.toString() +'</span> / ' + maxChar + '</div>');
		
		
		elm.bind("keyup", function() {

			var elmVal = elm.val();
			var elmLength = elmVal.length;
			
			if(elmLength > maxChar){
				elmVal = elmVal.substring(0, maxChar);
				elm.val(elmVal);
				alert(maxChar + ' Characters Maximum');

			}
			else {
				leftChar = maxChar - elmLength;
				$("div.counter").children(".counterChar" + obj).text(leftChar.toString());	
			}
	
		})
		
	});

}


/*
 * CLOSE BUTTON
 * Bind close function for element with ID btn_close (#btn_close)
 * ID : #btn_close
*/

function closePopup() {
	$("input#btn_close").each( function() {
		$(this).click(function() {
			self.close();
		});
	});
}

/*
 * POPUP WINDOW
 * Bind open new window function for element with ID openPopup (#openPopup)
 * Class: openPopup pop_[Width]x[Height]
 * To create popup 800x600, use class: openPopup pop_800x600
*/

function openPopup() {
	$("a.openPopup").each( function() {
		$(this).click(function() {
			
			var winpop;
			var xurl = $(this).attr('href');
			var xtarget = '_blank';
			var thisClass = $(this).attr('class').split(' ');
			var re = new RegExp('^(pop_)');
			for(i=0;i<thisClass.length;i++) {
				if(thisClass[i].match(re)) {
					popSizes = thisClass[i].split('_');
					popSize = popSizes[1].split('x');
					popWidth = popSize[0];
					popHeight = popSize[1];
				}
			}
			
			winpop = window.open(xurl, xtarget,'width=' + popWidth + ',height=' + popHeight + ',resizable=0,scrollbars=yes,menubar=no,status=no' );
			winpop.focus();
			return false;
		});
	});
}


/*
 * ADD TO FAVORITES
 * Class: bookmark
*/

function bookmark() {
	
	var sUrl = location.href;
	var sTitle = document.title;

	$(".bookmark").click(function(){
		if($.browser.msie) {
			window.external.AddFavorite(sUrl, sTitle); // IE/Win
		} else if($.browser.mozilla) {
			$(this).attr("title",sTitle);
		} else if($.browser.opera) {
			void(0);
		} else if($.browser.safari) {
			alert('You need to press CTRL/Cmd + D to bookmark our site.');	
		} else {
			alert('In order to bookmark this site you need to do so manually through your browser.');
		}
	});

}