
Number.prototype.formatMoney = function(c, d, t){
	var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};


function trim(s) {
	//return s.replace(/^\s*/, "").replace(/\s*$/, "");
	return s.strip();
}

function trimEle(eleId) {
	$(eleId).value = $(eleId).value.strip();
	//$(eleId).value = trim($(eleId).value);
}

function textareaMaxlength(element,maxLength) {
	if( element.value.length > maxLength ) {
		element.value = element.value.substring(0,maxLength);
	}
}

function isDigit(c) {
	return ((c>= '0') &&(c<= '9') );
}

function isCharacter() {
	if( event.keyCode >= 33 && event.keyCode <= 126)
		return true;		
}

function isRealNum(s) {
	
    var i;
    var seenDecimalPoint = false;
    var decimalPointDelimiter = '.';

    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);

        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }
    // All characters are numbers.
    return true;
}

function replaceZero( str ) {
	str = str.replace( /^[0]+/, '' );
	
	if( str.charAt(0) == '.' ) {
		str = '0' + str;
	}
	return str;
}

function isFloatNumber( element ) {
		
	var value = trim( element.value );
	
	if( value != '' ) {
	
		value = value.replace(/,/g ,'');
		value = value.replace(/\+/g ,'');
		value = value.replace(/\-/g ,'');
	
		if( isRealNum( value ) ){
			value = replaceZero(value);
			value = round_number(value,2);
			element.value = value;
			element.value = (parseFloat(value)).formatMoney(2, '.', ',');
			//return true;
		} else {
			element.value = '';
		}
	} else {
		element.value = '';
	}
}

function round_number(number, dec_places)
{
    //(c) Copyright 2008, Russell Walker, Netshine Software Limited. www.netshinesoftware.com   
    //Version 2.0. Change log:
    //18/12/08 Fixed bug where digits after decimal point greater than 995
    //29/01/09 Added support for negative numbers (symmetrical rounding) and strip white space
    //12/03/09 Fixed bug where first digit is a 9 and needs to be rounded up
    var new_number = '';
    var i = 0; //Just used in loops
    var sign = ""; //If negative, a minus sign will be prefixed to the result
    number = number.toString(); //We need to operate on and return a string, not a number
    number = number.replace(/^\s+|\s+$/g, ''); //Remove any excess white space
    
    //Do we have a negative number?
    if (number.charCodeAt(0) == 45) //minus sign
    {
        sign = '-';
        number = number.substr(1).replace(/^\s+|\s+$/g, '');
    }
    
    dec_places = dec_places * 1; //We need an integer
    dec_point_pos = number.lastIndexOf(".");
   
    //If there is nothing before the decimal point, prefix with a zero
    if (dec_point_pos == 0)
    {
        number = "0" + number;
        dec_point_pos = 1;
    }
   
    //Has an integer been passed in?
    if (dec_point_pos == -1 || dec_point_pos == number.length - 1)
    {
        if (dec_places > 0)
        {
            new_number = number + ".";
            for(i=0; i<dec_places; i++)
            {
                new_number += "0";
            }
            if (new_number == 0)
            {
                sign = "";
            }
            return sign + new_number;
        }
        else
        {
            return sign + number;
        }
    }
   
    //Do we already have the right number of decimal places?
    var existing_places = (number.length - 1) - dec_point_pos;
    if (existing_places == dec_places)
    {
        return sign + number; //If so, just return the input value
    }
   
    //Do we already have less than the number of decimal places we want?
    if (existing_places < dec_places)
    {
        //If so, pad out with zeros
        new_number = number;
        for(i=existing_places; i<dec_places; i++)
        {
            new_number += "0";
        }
        if (new_number == 0)
        {
            sign = "";
        }
        return sign + new_number;
    }
   
    //Work out whether to round up or not
    var end_pos = (dec_point_pos * 1) + dec_places;
    var round_up = false; //Whether or not to round up (add 1 to) the next digit along
    if ((number.charAt(end_pos + 1) * 1) > 4)
    {
        round_up = true;
    }
   
    //Record each digit in an array for easier manipulation
    var digit_array = new Array();
    for(i=0; i<=end_pos; i++)
    {
        digit_array[i] = number.charAt(i);
    }
   
    //Round up the last digit if required, and continue until no more 9's are found
    for(i=digit_array.length - 1; i>=0; i--)
    {
        if (digit_array[i] == ".")
        {
            continue;
        }
        if (round_up)
        {
            digit_array[i]++;
            if (digit_array[i] < 10)
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
   
    //Reconstruct the string, converting any 10's to 0's (except for first digit which can stay as a 10)
    for (i=0; i<=end_pos; i++)
    {
        if (digit_array[i] == "." || digit_array[i] < 10 || i == 0)
        {
            new_number += digit_array[i];
        }
        else
        {
            new_number += "0";
        }
    }
   
    //If there are no decimal places, we don't need a decimal point
    if (dec_places == 0)
    {
        new_number = new_number.replace(".", "");
    }
   
    if (new_number == 0)
    {
        sign = "";
    }
   
    //That should do it!
    return sign + new_number;
}

var StringBuffer = Class.create({

	initialize:function (string) {	
		this.buffer = [];
		this.buffer.push(string);
	},
	
	append: function(string) {
		this.buffer.push(string);
		return this
	},
	
	toString: function() {
		return this.buffer.join("");
	}
	
});	



function clearFile(eleId) {

	$(eleId+'Cover').innerHTML = '';
	
	var aLink = new Element('a', { href: 'javascript:;', onclick: 'clearFile("'+eleId+'")' } );
	var aLink = new Element('a', { href: 'javascript:clearFile("'+eleId+'");' } );	
	var imgButton = new Element('img', { 'src': './img/del.gif', 'class': 'noPadding' } );
	imgButton.wrap(aLink);	
	var fileInput = new Element('input', { 'type': 'file', 'id': eleId, 'name':'upload' } );
	
	$(eleId+'Cover').appendChild( fileInput );
	$(eleId+'Cover').appendChild( document.createTextNode(' ') );	
	$(eleId+'Cover').appendChild( aLink );
	
}

function setAllCheckBox(checkBoxId, formId, checkBoxName) {

	var form = $(formId);
	
	var checkboxs = form.getInputs('checkbox', checkBoxName);

	cCount = checkboxs.length;
	for( i = 0 ; i < cCount ; i++ ) {
		checkboxs[i].checked = $(checkBoxId).checked;
	}
}

function selectAllCheckBox(formId, checkBoxName) {

	var form = $(formId);
	
	var checkboxs = form.getInputs('checkbox', checkBoxName);

	cCount = checkboxs.length;
	for( i = 0 ; i < cCount ; i++ ) {
		checkboxs[i].checked = true;
	}
}

function deselectAllCheckBox(formId, checkBoxName) {

	var form = $(formId);

	var checkboxs = form.getInputs('checkbox', checkBoxName);

	cCount = checkboxs.length;

	for( i = 0 ; i < cCount ; i++ ) {
		checkboxs[i].checked = false;
	}
}


function setCheckBox(checkBoxId) {

	if( $(checkBoxId).checked ) {
		$(checkBoxId).checked = false;
	} else {
		$(checkBoxId).checked = true;	
	}
}

function clearList(eleId) {

	var len = $(eleId).options.length;
	if( len > 0 ) {
		for( i = 0; i < len ; i++ ) {
			$(eleId).options[i].selected = false;
		}		
	}
}

function convertSpaceUnit() {
	
	$('waUnit').value = '';
	if( $('convertWaUnitBox').checked ) {
		Effect.BlindDown('waUnitSpan', { duration: 0.5 });
	} else {
		Effect.BlindUp('waUnitSpan', { duration: 0.5 });
	}
}

function convertWaUnit() {

	var waUnit = trim($('waUnit').value);
	if( waUnit != '' ) {
		waUnit = waUnit.replace(/,/g ,'');
		waUnit = waUnit.replace(/\+/g ,'');
		waUnit = waUnit.replace(/\-/g ,'');
		waUnit = round_number(waUnit * 4,2);
		$('space').value = (parseFloat(waUnit)).formatMoney(2, '.', ',');
		$('convertWaUnitBox').checked = false;
		convertSpaceUnit();
	}
}

function serchPriceOption() {

	$('price').value = '';
	$('adsPricePeriod').value = '';
	
	if( $('searchByPriceOption').checked ) {
		$('price').readOnly = true;
		$('price').setStyle( {backgroundColor: '#f2f0f0'});
		$('adsPricePeriod').disabled = false;
		$('adsPricePeriod').setStyle( {backgroundColor: '#ffffff'});
		$('adsPricePeriod').focus();
	} else {
		$('price').readOnly = false;
		$('price').setStyle( {backgroundColor: '#ffffff'});
		$('price').focus();
		$('adsPricePeriod').disabled = true;
		$('adsPricePeriod').setStyle( {backgroundColor: '#f2f0f0'});
	}
}

function serchSpaceOption() {

	$('space').value = '';
	$('adsSpacePeriod').value = '';
	$('convertWaUnitBox').checked = false;
	convertSpaceUnit();
	
	if( $('searchBySpaceOption').checked ) {
		$('space').readOnly = true;
		$('space').setStyle( {backgroundColor: '#f2f0f0'});
		$('adsSpacePeriod').disabled = false;
		$('adsSpacePeriod').setStyle( {backgroundColor: '#ffffff'});
		$('convertWaUnitBox').onclick = null;
	} else {
		$('space').readOnly = false;
		$('space').setStyle( {backgroundColor: '#ffffff'});
		$('adsSpacePeriod').disabled = true;
		$('adsSpacePeriod').setStyle( {backgroundColor: '#f2f0f0'});
		$('convertWaUnitBox').onclick = convertSpaceUnit;
	}
}

function mouseOverDelIcon(divIcon) {
	divIcon.className = 'delIcon';
}
function mouseOutDelIcon(divIcon) {
	divIcon.className = 'delIcon_';
}

function removeBgColor(eleId) {
	$(eleId).setStyle( {backgroundColor: '#ffffff'});

}

function setBgColor(eleId,color) {
	$(eleId).setStyle( {backgroundColor: color});
}

function pausecomp(millis) {
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); }
	while(curDate-date < millis);
	
	date = null;
	curDate = null;
} 

function isDigit(testValue) {	
	return !/[^\d]/.test(testValue);
}

/*
//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}


//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}



// show loading progress screen
function showLoadingScreen() {

	var showMessage = 'Please Wait ...';
	showMessage = 'กรุณารอสักครู่...';
	if( arguments.length == 1 ) {
		showMessage = arguments[0];
	}

	hideSelectBoxes();
	hideFlash();
		
	//set grey layer
	if( $('loadingOverlay') == null ) {
		var body = document.getElementsByTagName("body").item(0);
		var overlay = document.createElement("div");
		overlay.setAttribute('id','loadingOverlay');
		body.appendChild(overlay);
	}
	$('loadingOverlay').style.display = 'none';
	
	//set container of message and progress bar
	if( $('loadingContainer') == null ) {
		var loadingContainer = document.createElement("div");
		loadingContainer.setAttribute('id','loadingContainer');
		loadingContainer.style.display = 'none';
		body.appendChild(loadingContainer);
	}
	
	// set show message div
	if( $('loadingMessage') == null ) {
	
	
		var rbroundbox = new Element( 'div', {'class':'rbroundbox'} );
		var rbtop = new Element( 'div', {'class':'rbtop'} );
		rbtop.appendChild( new Element( 'div' ) );
		
		var rbcontent = new Element( 'div', {'class':'rbcontent'} );
		
		var rbbot = new Element( 'div', {'class':'rbbot'} );
		rbbot.appendChild( new Element( 'div' ) );
		
		rbroundbox.appendChild( rbtop );
		rbroundbox.appendChild( rbcontent );
		rbroundbox.appendChild( rbbot );

	
		//set progress bar
		var loadingImage = null;
		if( $('loadingImage') == null ) {
			loadingImage = new Element( 'div', {'id':'loadingImage'} );
		}
		
		//var roundcont = new Element( 'div', {'class': 'roundcont','style':'margin-left: auto;margin-right: auto;'} );
		//var roundtop = new Element( 'div', {'class': 'roundtop' } );
		//var tl = new Element('img', {'src': '.././images/roundbox/tl.gif', 'width':'15','height':'15','class':'corner','style':'display:none;'});
		//roundtop.appendChild(tl);
		
		//var roundTopLeft = new Element( 'div', {'class':'roundtopLeft'} );
		
		
		var message = new Element( 'p' ).update( showMessage);
		//var roundbottom = new Element( 'div', {'class': 'roundbottom' } );
		//var bl = new Element('img', {'src': '.././images/roundbox/bl.gif', 'width':'15','height':'15','class':'corner','style':'display:none'});
		//roundbottom.appendChild(bl);
		//roundcont.appendChild(roundtop);
		//roundcont.appendChild(message);
		//roundcont.appendChild(loadingImage);
		//roundcont.appendChild(roundbottom);
		
		//var loadingMessage = new Element( 'div', {'id': 'loadingMessage' } );
		//var loadingMessage = document.createElement("div");
		//loadingMessage.setAttribute('id','loadingMessage');
		//loadingMessage.innerHTML = '<p>'+ showMessage +'</p>';
		//loadingMessage.innerHTML = roundBox;
		//loadingMessage.appendChild( roundcont );
		
		//$('loadingContainer').appendChild(loadingMessage);
		rbcontent.appendChild(message);
		rbcontent.appendChild(loadingImage);
		$('loadingContainer').appendChild(rbroundbox);
		
	}
	
	//var alertBox = new AlertBox('MSG_INFO','pls wait');
	//$('loadingContainer').appendChild(alertBox.getBoxElement());

	// When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
	// If animations are turned off, it will be hidden as to prevent a flicker of a
	// white 250 by 250 box.
	//if(animate){
	//	Element.setWidth('outerImageContainer', 250);
	//	Element.setHeight('outerImageContainer', 250);			
	//}
	
	
	
	// calculate top offset for the lightbox and display 
	var arrayPageSize = getPageSize();


	Element.setHeight('loadingOverlay', arrayPageSize[1]);
	new Effect.Appear('loadingOverlay', { duration: 0.4, from: 0.0, to: 0.4 });
	
	var arrayPageScroll = getPageScroll();
	var topPosition = arrayPageScroll[1] + (arrayPageSize[3] / 3); // arrayPageSize[3] / 10

	Element.setTop('loadingContainer', topPosition);
	Element.show('loadingContainer');
	
	Event.observe(window, 'scroll', moveLoadingScreen );

}

function moveLoadingScreen() {
	arrayPageSize = getPageSize();
	arrayPageScroll = getPageScroll();
	topPosition = arrayPageScroll[1] + (arrayPageSize[3] / 3); // arrayPageSize[3] / 10
	new Effect.Move('loadingContainer', { y: topPosition, mode: 'absolute' });	
}


// to stop show loading screen

function hideLoadingScreen() {

	Event.stopObserving(window, 'scroll', moveLoadingScreen );
	
	if( $('loadingContainer') != null ) {		
		Element.hide('loadingContainer');
	}
	
	if( $('loadingOverlay') != null ) {
		new Effect.Fade('loadingOverlay', { duration: 0.4});
	}
	showSelectBoxes();
	showFlash();

}


function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

// ---------------------------------------------------

function showFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i != flashObjects.length; i++) {
		flashObjects[i].style.visibility = "visible";
	}

	var flashEmbeds = document.getElementsByTagName("embeds");
	for (i = 0; i != flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i != flashObjects.length; i++) {
		flashObjects[i].style.visibility = "hidden";
	}

	var flashEmbeds = document.getElementsByTagName("embeds");
	for (i = 0; i != flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "hidden";
	}

}

function alertErrorMsg(messageArray) {

	// hide loading screen if exist
	hideLoadingScreen();
	
	hideSelectBoxes();
	hideFlash();
		
	//set grey layer
	
	if( $('alertOverlay') == null ) {
		var body = document.getElementsByTagName("body").item(0);
		var alertOverlay = document.createElement("div");
		alertOverlay.setAttribute('id','alertOverlay');
		body.appendChild(alertOverlay);
		
	}
	$('alertOverlay').style.display = 'none';
	
	//set container of message and progress bar

	if( $('alertContainer') == null ) {
		var body = document.getElementsByTagName("body").item(0);
		var alertContainer = document.createElement("div");
		alertContainer.setAttribute('id','alertContainer');
		alertContainer.style.display = 'none';
		body.appendChild(alertContainer);		
	}

	
	// set show message div
	if( $('alertMessage') == null ) {
		var alertMessage = document.createElement("div");
		alertMessage.setAttribute('id','alertMessage');
		
		$('alertContainer').appendChild(alertMessage);
		
		var closeB = document.createElement("input");
		closeB.type = 'button';
		closeB.value = 'ปิด';
		closeB.onclick = function() {
			Event.stopObserving(window, 'scroll', moveAlertScreen );
			
			if( $('alertContainer') != null ) {
				Element.hide('alertContainer');
			}
			if( $('alertOverlay') != null ) {
				new Effect.Fade('alertOverlay', { duration: 0.4});
			}
			showSelectBoxes();
			showFlash();
		}
		
		$('alertContainer').appendChild(closeB);
		
	}
	$('alertMessage').innerHTML = '<p>'+ messageArray[0] +'</p>';

	
	// calculate top offset for the lightbox and display 
	var arrayPageSize = getPageSize();
	Element.setHeight('alertOverlay', arrayPageSize[1] );
	new Effect.Appear('alertOverlay', { duration: 0.4, from: 0.0, to: 0.3 });
	
	var arrayPageScroll = getPageScroll();
	var topPosition = arrayPageScroll[1] + (arrayPageSize[3] / 3); // arrayPageSize[3] / 10
	
	//alert( topPosition );
	Element.setTop('alertContainer', topPosition );
	Element.show('alertContainer');	
	Event.observe(window, 'scroll', moveAlertScreen );
}


function moveAlertScreen() {
	arrayPageSize = getPageSize();
	arrayPageScroll = getPageScroll();
	topPosition = arrayPageScroll[1] + (arrayPageSize[3] / 3); // arrayPageSize[3] / 10	
	
	new Effect.Move('alertContainer', { y: topPosition, mode: 'absolute' });
}

function createBoxConfirm() {

	var box = new Element('div', {'id':'SexyAlertBox-Box','style':'display: block; z-index: 65557; margin-left: auto; margin-right: auto; width: 500px;'} );
	var inBox = new Element('div', {'id':'SexyAlertBox-InBox'});
	
	var boxContent = new Element('div', {'id':'SexyAlertBox-BoxContent'});	
	var boxContenedor = new Element('div',{'id':'SexyAlertBox-BoxContenedor', 'class':'BoxPrompt'} );
	
	var messageArea = new Element('div');
	boxContenedor.appendChild(messageArea);
	
	box.messageArea = messageArea;
	var buttons = new Element('div',{'id':'SexyAlertBox-Buttons'});
		
	var okButton = new Element('input', {'id':'BoxPromptBtnOk', 'class':'button', 'type':'button', 'value':'OK', 'style':'width: 70px;'});
	box.okButton = okButton;
	var cancelButton = new Element('input', {'id':'BoxPromptBtnCancel', 'class':'button', 'type':'button', 'value':'CANCEL', 'style':'width: 70px;'});
	box.cancelButton = cancelButton;
	
	buttons.appendChild(okButton);
	buttons.appendChild(cancelButton);
	
	boxContenedor.appendChild( buttons );
	boxContent.appendChild(boxContenedor);
	inBox.appendChild(boxContent);  
	box.appendChild(inBox);
	
	return box;
	
}

*/