
var checkflag = "false";
/*
Usage: to check all checkbox
*/
function check(field) {
  if (checkflag == "false") {
    for (i = 0; i < field.length; i++) {
      field[i].checked = true;
    }
    checkflag = "true";
    return "X";
  } else {
    for (i = 0; i < field.length; i++) {
      field[i].checked = false;
    }
    checkflag = "false";
    return "X";
  }
}
// to make the checkbox readonly, dont allow  user to deselect the checkbox
function readOnlyCheckBox() {
  return false;
}

function showLayer(id){
  document.getElementById(id).style.display = "block";
}

function showMenu(id){
  document.getElementById(id).style.display = "block";
  document.getElementById(id).className = "left-menu-selected";
}
function showPlaftform(id,linkAddress1){
  document.getElementById(id).style.display = "block";
  document.getElementById("linkAddress").value = linkAddress1;
}

function hideLayer(id){
  document.getElementById(id).style.display = "none";
}

function showHide(id){
  var layerDisplay = document.getElementById(id).style.display;
  if (layerDisplay == "none"){
    document.getElementById(id).style.display = "block";
  }else if (layerDisplay == "block") {
    document.getElementById(id).style.display= "none";
  }
}

function confirmDelete(message) {
  return confirm(message);
}

function confirmDelete2(message, url) {
	if (confirm(message)){
		window.location.href=url;
	}
}

function isEmpty(str) {
  if( str == null || str == ""){
    return true;
  }
  var returnValue = true;
  var len = str.length;
  for( i=0; i<len; i++ ) {
    if( str.charAt(i) != " ")
      returnValue = false;
  }
  return returnValue;
}

function highlightAll(id){
  document.getElementById(id).focus();
  document.getElementById(id).select();
}

// select / unselect all checkbox
// usage : checkUncheckAll(this), will select all checkbox in this form
function checkUncheckAll2(theElement) {
  var theForm = theElement.form, z = 0;
  for(z=0; z<theForm.length;z++){
    if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall'){
      theForm[z].checked = theElement.checked;
    }
  }
}

/*
select/unselect all checkbox, by the checkbox name
usage : checkUncheckAll(this, platformSearch, platformAll);
this : form | platformSearch : the name of checkboxes | platformAll : name of the select/deselect all checkbox
*/
function checkUncheckAll(thisForm, fieldName, checkAllName) {
  with (thisForm){
    for(z=0; z<fieldName.length;z++){
      if (checkAllName.checked){
        fieldName[z].checked = true;
      }else{
        fieldName[z].checked = false;
      }
    }
    }
}


function select_all(name){
  var selectedAll = "false";
  var forminputs = document.applicationNewUploadForm.getElementsByTagName('input');
  for (i = 0; i < forminputs.length; i++){
    // regex here to check name attribute

    var regex = new RegExp(name, "i");
    if (regex.test(forminputs[i].getAttribute('name'))){
      var slect = document.applicationNewUploadForm.elements['selectAll'];
      if(selectedAll == "false" && slect.checked==true){
        forminputs[i].checked = true;
      }else{
        forminputs[i].checked = false;
      }
    }
  }
  if(selectedAll == "false"){
    selectedAll = "true";
  }else{
    selectedAll = "false";
  }
}

function copyTo(value, id){
  document.getElementById(id).value = "";
  document.getElementById(id).value = value;
}

// check uploaded Apps
function checkApps(){

  var something = document.getElementById("filesApps").innerHTML;
  var defaultThere = document.getElementById("defaultThere").value;

  if (isEmpty(something)){
    alert("No Apps is uploaded");
    return false;
  }

  if (defaultThere == 0){
    alert("No default picture");
    return false;
  }

}

function activateAccount(){
	document.activate.submit();
}

function checkUserSession(userId){
	  if (userId==0){
    document.getElementById("claimAppError").innerHTML = "<a href='javascript:void(0)' onclick='showLayer(\"loginBox\")' style='font-size:12px;'>Login</a> to claim your app!";
    return false;
		}
}

/* for onblur checking */

function isValidName(id, errId) {
  var str=document.getElementById(id).value;
  if(!isEmpty(str)){
    document.getElementById(errId).innerHTML = "";

  } else {
    document.getElementById(errId).innerHTML = "<span class=\"warning bold\"> Your name must be filled out!</span>";

  }
}

/* for onblur checking */

function isValidExplaination(id, errId) {
  var str=document.getElementById(id).value;
  if(!isEmpty(str)){
    document.getElementById(errId).innerHTML = "";

  } else {
    document.getElementById(errId).innerHTML = "<span class=\"warning bold\"> Your explaination must be filled out!</span>";

  }
}

/* for onblur checking */
function isValidEmail(id, errId) {
  var str=document.getElementById(id).value;
  str = str.replace(" ","");
  var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
  if(!isEmpty(str)){
    if (filter.test(str)){
      document.getElementById(errId).innerHTML = "";
    }else{
      document.getElementById(errId).innerHTML = "<span class=\"warning bold\"> Invalid email address.</span>";
    }
  } else {
    document.getElementById(errId).innerHTML = "<span class=\"warning bold\"> Please fill in the email address.</span>";

  }
}

/* check all values are integer */
function checkInt(id, errId){
  var input = document.getElementById(id).value;
  s = new String(input);
  x = s.replace(/-/g,"");
  var validFormatRegExp = /^((\+|-)\d)?\d*$/;
  if (validFormatRegExp.test(x) == false){
    document.getElementById(errId).innerHTML = " Only numeric number";
  }else{
    document.getElementById(errId).innerHTML = "";
  }
}

function validate_required(field,alerttxt){
  with (field){
    if (value==null||value==""){
      x = field.name+"Error";
      document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
      return false;
    }else if (value=="http://"){
      x = field.name+"Error";
      document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
      return false;
    }else if (value=="example.com"){
      x = field.name+"Error";
      document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
      return false;
    }else {
      return true
    }
    }
}

function validate_checkbox_required(field, alerttxt){
  with (field){
    if (field.checked==false){
      x = field.name+"Error";
      document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
      return false;
    }
    else {
      return true
    }

    }
}

function validate_radio_required(field,errorDiv, alerttxt){
  var show = false;
  for (var i=0;i<field.length;i++){
    if (field[i].checked){
      show = true;
    }
  }
  if (show==true){
    return true;
  }else{
    document.getElementById(errorDiv).innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
    return false;
  }
}

function validate_url(field, alerttxt) {
	with (field){
		var urlregex = /^(!:http:\/\/)?(?:[\w-]+\.)+[a-z]{2,6}$/i;	// only www.abc.com format accepted
		if(!urlregex.test(value)){
			x = field.name+"Error";
      document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
			return false;
		}else{
			x = field.name+"Error";
      document.getElementById(x).innerHTML = "";
			return true;
		}
	}
}

function isValidLoginX(id, message){
  //var illegal = /^[\w\-\.\+]+\[0-9a-zA-Z]+$/;
  var illegal = /\W/;
  var xx = document.getElementById(id).value;
  if(xx.match(illegal)){
    return false;
  }else{
    return true;
  }
}


function isValidLogin(field, message){
  //var illegal = /^[\w\-\.\+]+\[0-9a-zA-Z]+$/;
  var illegal = /\W/;
  if(field.value.match(illegal)){
    x = field.name+"Error";
    document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+message+"</span>";
    return false;
  }else{
    return true;
  }
}

/* for onsubmit checking */

function isEmailValid(field, message){
  var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

  if(field.value.match(emailExp)){
    return true;
  }else{
    x = field.name+"Error";
    document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+message+"</span>";
    return false;
  }
}

function isPasswordValid(field, stateError){

  var password = document.getElementById(field).value;
  if (password.length == 0){
	document.getElementById(stateError).innerHTML = "<span  class=\"warning bold\"> Password is Empty! </span>";
  }else{
	  if ((password.length < 6) || (password.length > 32)){
		document.getElementById(stateError).innerHTML = "<span  class=\"warning bold\"> Use 6 to 32 characters. </span>";
		return false;
	  }else{
		document.getElementById(stateError).innerHTML = "";
	  }
  }

  return true;
}

function isEmailValidInstant(field, message){
  var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
  x = field+"Error";

  if(document.getElementById(field).value.match(emailExp)){
    document.getElementById(x).innerHTML = "";
    return true;
  }else{
    document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+message+"</span>";
    return false;
  }
}

function isPhoneValid(field, message){

  if(isWithoutAlpha(field)){
    return true;
  }else{
    x = field.name+"Error";
    document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+message+"</span>";
    return false;
  }
}

function isPhoneValidInstant(field, message){
  x = field+"Error";

  if(isWithoutAlpha(document.getElementById(field))){
    document.getElementById(x).innerHTML = "";
    return true;
  }else{
    document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+message+"</span>";
    return false;
  }
}

function isZipcodeValid(field, message){

  if(isWithoutAlpha(field)){
    return true;
  }else{
    x = field.name+"Error";
    document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+message+"</span>";
    return false;
  }
}

function isZipcodeValidInstant(field, message){
  x = field+"Error";

  if(isWithoutAlpha(document.getElementById(field))){
    document.getElementById(x).innerHTML = "";
    return true;
  }else{
    document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+message+"</span>";
    return false;
  }
}

/*Aiwei : validate the first char is not space*/
function validate_space(field,alerttxt){
  with (field){
    if (value.indexOf(' ')==0){
      x = field.name+"Error";
      document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
      return false;
    }
  }
}

/*Aiwei : validate widget title*/
function validate_title(field,alerttxt){
  with (field){
    var titleExpression = /^[a-zA-Z0-9 ]+$/;
    if(!(value.match(titleExpression))){
      x = field.name+"Error";
      document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
      return false;
    }
    }
}
/*Aiwei : validate widget color code*/
function validate_color(field,alerttxt){
  with (field){
    var titleExpression = /^(#)?([0-9a-fA-F]{3})([0-9a-fA-F]{3})?$/;
    if(!(value.match(titleExpression))){
      x = field.name+"Error";
      document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
      return false;
    }
    }
}

/*Shaorn: show Widget custom size pane */
function toggleCustomSizePanel(el){
  if (el.item(el.selectedIndex).text.match((/custom/i))){
	togglePanelsById(['custom'],1);
  }else{
	togglePanelsById(['custom'],0);
  }
}

function togglePanelsById(targets,viewState){
	var i = typeof targets === 'object'?targets.length:false;
	var states = [
				  "none",
				  "block",
				  "inline-block",
				  "run-in",
				  "table",
				  "table-caption",
				  "table-cell",
				  "table-column",
				  "table-column-group",
				  "table-row",
				  "table-row-group",
				  "inherit"];
	viewState = parseInt(viewState)!='NaN' && states[parseInt(viewState)]!='undefined'?parseInt(viewState):0;
	if (i){
	  while (i--){
		a = document.getElementById(targets[i]);
		if (a){
		  a.style.display = states[viewState];
		}
	  }
	  return true;
	}else{
	  return false;
	}
}

/*Boon Sheng : validate registeration password*/
function validate_password(value, value2, errorDiv){
	var min =6;
	var max = 32;
	document.getElementById(errorDiv).innerHTML = "";
	if ((value.length < min) || (value.length > max) ){
		document.getElementById(errorDiv).innerHTML =  " Use 6 to 32 characters. ";
		/* <img src=\"images/wrong.png\"> Use 6 to 32 characters. ;*/
	}else	if (isEmpty(value)){
		document.getElementById(value2).value = "";
		document.getElementById(errorDiv).innerHTML = clear+" is empty!";
		/* <img src=\"images/wrong.png\"> "+clear+" is empty!;*/
		return false;
	}
  return true;
}

function pastePassword(id1,id2)
{
  document.getElementById(id2).value = document.getElementById(id1).value;
}

/*
function error(err){
	if(err.match(true)){
		return true;
	} else{
		return false;
	}
}
*/

function isNumeric(field, message){
  var numericExpression = /^[0-9]+$/;
  if(field.value.match(numericExpression)){
    return true;
  }else{
    x = field.name+"Error";
    document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+message+"</span>";
    return false;
  }
}

function isPrice(field, message){
  var numericExpression = /^\d*(?:\.\d{0,2})?$/;  /* /[0-9.,]+/;*/
  if(field.value.match(numericExpression)){
    return true;
  }else{
    x = field.name+"Error";
    document.getElementById(x).innerHTML = "<span class=\"warning bold\"> "+message+"</span>";
    return false;
  }
}

function isNumber(field){
  var numericExpression = /^[0-9]+$/;
  if(field.value.match(numericExpression)){
    return true;
  }else{
    return false;
  }
}

function isWithoutAlpha(field){
  var alphaExpression = /^[^a-zA-Z]+$/;
  if(field.value.match(alphaExpression)){
    return true;
  }else{
    return false;
  }
}


function validate_aff_form(thisform) {
  var lengthy = document.advertisePrice.selectUrl.length;
  for (var x=0;x<lengthy;x++){
    if (document.advertisePrice.selectUrl[x].checked){
      var idValue = document.advertisePrice.selectUrl[x].value;

      if (isEmpty(document.getElementById("totalPerClick_"+idValue).value)){
        document.getElementById("statusError").className ="bold warning";
        document.getElementById("statusError").innerHTML ="total Per click";
        document.getElementById("totalPerClick_"+idValue).focus();
        return false;
      }

      if (isPrice(document.getElementById("totalPerClick_"+idValue))==false){
        document.getElementById("statusError").className ="bold warning";
        document.getElementById("statusError").innerHTML ="price!!";
        document.getElementById("totalPerClick_"+idValue).focus();
        return false;
      }

      if (isEmpty(document.getElementById("totalClicks_"+idValue).value)){
        document.getElementById("statusError").className ="bold warning";
        document.getElementById("statusError").innerHTML ="total impression";
        document.getElementById("totalClicks_"+idValue).focus();
        return false;
      }

      if (isNumber(document.getElementById("totalClicks_"+idValue))==false){
        document.getElementById("statusError").className ="bold warning";
        document.getElementById("statusError").innerHTML ="numeric!!";
        document.getElementById("totalClicks_"+idValue).focus();
        return false;
      }
    }
  }
}



/*
Usage : onsubmit check in resend_activation.jsp , password_forgot.jsp, contact_us.jsp, contact_us_public.jsp
*/
function validate_checkEmail_form(thisform){
  with (thisform){
    if (validate_required(email,"Email must be filled out!")==false)
    {
      email.focus();
      return false;
    }
    if (isEmailValid(email, "Invalid email address.")==false)
    {
      email.focus();
      return false;
    }
    }
}

function validate_contact_form(thisform){
  with (thisform){
    if (validate_required(name,"Name must be filled out!")==false)
    {
      name.focus();
      return false;
    }
    if (validate_required(email,"Email must be filled out!")==false)
    {
      email.focus();
      return false;
    }
    if (isEmailValid(email, "Invalid email address.")==false)
    {
      email.focus();
      return false;
    }
    if (validate_required(message,"Message must be filled out!")==false)
    {
      message.focus();
      return false;
    }
    }
}

function validate_feedback_form(){
  var fuserId = document.getElementById("fuserId").value;
  var fname = document.getElementById("fname").value;
  var femail = document.getElementById("femail").value;
  var fmessage = document.getElementById("fmessage").value;
  var ftype = document.getElementById("ftype").value;

  if (validate_required(document.getElementById("fname"),"Name must be filled out!")==false)
  {
    document.getElementById("fname").focus();
    return false;
  }
  if (validate_required(document.getElementById("femail"),"Email must be filled out!")==false)
  {
    document.getElementById("femail").focus();
    return false;
  }
  if (isEmailValid(document.getElementById("femail"), "Invalid email address.")==false)
  {
    document.getElementById("femail").focus();
    return false;
  }
  if (validate_required(document.getElementById("fmessage"),"Message must be filled out!")==false)
  {
    document.getElementById("fmessage").focus();
    return false;
  }

  sendFeedback();
}

function validate_package_form(thisform){
  with (thisform){
    if (validate_required(billName,"Name must be filled out!")==false)
    {
      billName.focus();
      return false;
    }
    if (validate_required(billEmail,"Email must be filled out!")==false)
    {
      billEmail.focus();
      return false;
    }
    if (isEmailValid(billEmail, "Invalid email address.")==false)
    {
      billEmail.focus();
      return false;
    }
    if (validate_required(billMobile, "Mobile number must be filled out!")==false)
    {
      billMobile.focus();
      return false;
    }
    if (validate_required(billDesc,"Description must be filled out!")==false)
    {
      billDesc.focus();
      return false;
    }
    }
}

function validate_password_form(thisform){
  with (thisform){
    if (validate_required(oldPassword,"Old Password must be filled out!")==false)
    {
      oldPassword.focus();
      return false;
    }

    if (validate_required(passwordn,"Password must be filled out!")==false)
    {
      passwordn.focus();
      return false;
    }
    /*if (checkNicknameLength("password", "passwordError", 6, 32, "Password")==false)
			{return false;}*/
    if (validate_required(passwordv,"Please retype your password.")==false)
    {
      passwordv.focus();
      return false;
    }

    if (isPasswordValid("oldPassword","oldPasswordError")==false)
    {
      oldPassword.focus();
      return false;
    }

    if (isPasswordValid("passwordn","password_1Error")==false)
    {
      passwordn.focus();
      return false;
    }

    if (isPasswordValid("passwordv","password_2Error")==false)
    {
      passwordv.focus();
      return false;
    }

    /*if (checkNicknameLength("password2", "password2Error", 6, 32, "Password")==false)
			{return false;}*/
    if (checkEqualPassword("passwordn", "passwordv", "password_1Error", "password_2Error")==false)
    {
      return false;
    }

    old_password.value=hex_md5_update(oldPassword.value, "oldPassword", "old_password", "oldPasswordError");
    password_1.value=hex_md5_update(passwordn.value, "passwordn", "password_1", "password_1Error");
    password_2.value=hex_md5_update(passwordv.value, "passwordv", "password_2", "password_2Error");
  }
}

function validate_domain_form(thisform){
  with (thisform){
    if (validate_required(url,"URL must be filled out!")==false)
    {
      url.focus();
      return false;
    }
		if (validate_url(url,"URL must be in www.abc.com format")==false)
    {
      url.focus();
      return false;
    }
    if (validate_required(country,"Country must be filled out!")==false)
    {
      country.focus();
      return false;
    }
    if (validate_required(name, "Name must be filled out!")==false)
    {
      name.focus();
      return false;
    }
    if (validate_required(categoryId,"Category must be filled out!")==false)
    {
      categoryId.focus();
      return false;
    }
    }
}

function copyButtonValue(source, target){
	var a = document.getElementById(source);
	var b = document.getElementById(target);
	b.value = a.value;
}


/* validate mandatory fields in get_codes.jsp */
function validate_widget_form(thisform){
  with (thisform){
    var Page1hasError = false;
    var Page2hasError = false;

    if (validate_required(txt_widgetTitle,"Widget Name must be filled out!<br/>")==false)
    {
      txt_widgetTitle.style.backgroundColor="#FFEDEF";
      Page1hasError = true;
    }
    else{
			if (selectedButton.value=="Save as New Widget & Get Codes"){
				if (txt_widgetTitle.value == txt_widgetTitleOri.value){
					document.getElementById("txt_widgetTitleError").innerHTML = "<span  class=\"warning bold\"> Widget name has been taken. Please use another name.</span>";
					Page1hasError = true;
				}
			}else{
				txt_widgetTitle.style.backgroundColor="#FFFFFF";
				document.getElementById("txt_widgetTitleError").innerHTML = "";
			}
    }

    if (validate_required(affiliateUrlId,"Require at least one domain to create widget. Click <a href=\"domain_add.jsp\"><u>here</u></a> to create domain.<br/>")==false)
    {
      affiliateUrlId.style.backgroundColor="#FFEDEF";
      Page1hasError = true;
    }
    else{
      affiliateUrlId.style.backgroundColor="#FFFFFF";
      document.getElementById("affiliateUrlIdError").innerHTML = "";
    }

    if (validate_required(keywords,"Minimum one keyword must be filled out!")==false)
    {
      keywords.style.backgroundColor="#FFEDEF";
      Page2hasError = true;
    }
    else{
      keywords.style.backgroundColor="#FFFFFF";
      document.getElementById("keywordsError").innerHTML = "";
    }

    var platformChecked = 0;
    for (counter = 0; counter < platform.length; counter++){
      if (platform[counter].checked){
        platformChecked += 1;
      }
    }
    if (platformChecked==0){
      document.getElementById("platformError").innerHTML = "<span class=\"warning bold\">Select at least 1 Platform</span>";
      Page2hasError = true;
    }
    else{
      document.getElementById("platformError").innerHTML = "";
    }

    var $link1 = $('#navigation li:nth-child(1) a');
		$link1.parent().find('.error,.checked').remove();
    if(Page1hasError)
      $('<span class="error"></span>').insertAfter($link1);
    else
      $('<span class="checked"></span>').insertAfter($link1);

    var $link2 = $('#navigation li:nth-child(2) a');
		$link2.parent().find('.error,.checked').remove();
    if(Page2hasError)
      $('<span class="error"></span>').insertAfter($link2);
    else
      $('<span class="checked"></span>').insertAfter($link2);

    if(Page1hasError || Page2hasError){
			return false;
		}
  }
}

function validate_widget_form1(){
  with(document.forms['formElem']){
    if (validate_required(txt_widgetTitle,"Widget Name must be filled out!<br/>")==false)
    {
      txt_widgetTitle.style.backgroundColor="#FFEDEF";
      return "error";
    }

    if (validate_required(affiliateUrlId,"Require at least one domain to create widget. Click <a href=\"domain_add.jsp\"><u>here</u></a> to create domain.<br/>")==false)
    {
      affiliateUrlId.style.backgroundColor="#FFEDEF";
      return "error";
    }
    return "checked";
  }
}

function validate_widget_form2(){
    with(document.forms['formElem']){
    if (validate_required(document.getElementById("keywords"),"Minimum one keyword must be filled out!")==false)
    {
      document.getElementById("keywords").style.backgroundColor="#FFEDEF";
      return "error";
    }

    var platformChecked = 0;
    for (counter = 0; counter < platform.length; counter++){
      if (platform[counter].checked){
        platformChecked += 1;
      }
    }
    if (platformChecked==0){
      document.getElementById("platformError").innerHTML = "<span class=\"warning bold\">Select at least 1 Platform</span>";
      return "error";
    }
    return "checked";
    }
}

/*
Usage : onsubmit check in profile.jsp
*/
function validate_profile_form(thisform){
  with (thisform){
    if (validate_required(name,"Name must be filled out!")==false)
    {
      name.focus();
      return false;
    }
    }
}



/* validate mandatory fields in advertise.jsp */
function validate_advertise_form(thisform){
  with (thisform){
    if (validate_required(adsName,"Title must be filled out!")==false)
    {
      adsName.focus();
      return false;
    }
    if (validate_required(adsDescription,"Description must be filled out!")==false)
    {
      adsDescription.focus();
      return false;
    }
    // if location WW is unchecked, means MUST select country
    //if (location[0].checked == false){
    if (validate_required(countryCode,"Country Code must be filled out!")==false)
    {
      countryCode.focus();
      return false;
    }
    //}
    }
}

function validate_landing_form(thisform){
  with (thisform){
    if (validate_required(name,"Your name must be filled out!")==false)
    {
      name.focus();
      return false;
    }

    if (validate_required(email,"Email must be filled out!")==false)
    {
      email.focus();
      return false;
    }

    if (isEmailValid(email,"Invalid email address.")==false)
    {
      email.focus();
      return false;
    }

    if (validate_required(password1,"Password must be filled out!")==false)
    {
      password1.focus();
      return false;
    }

    if (isPasswordValid("password1","password1Error")==false)
    {
      password1.focus();
      return false;
    }

    if (validate_required(password2,"Retype the password.")==false)
    {
      password2.focus();
      return false;
    }

    if(checkEqualPassword("password1", "password2","password1Error", "password2Error")==false)
    {
      password2.focus();
      return false;
    }

    if (validate_checkbox_required(agree,"You must agree on the Terms & Conditions to continue")==false)
    {
      agree.focus();
      return false;
    }

    password_1.value=hex_md5_update(password1.value, 'password1', 'password_1', 'password1Error');
		password_2.value=hex_md5_update(password2.value, "password2", "password_2", "password2Error");
    }
}

function validate_activation_form(thisform){
  with (thisform){
    if (validate_required(name,"Your name must be filled out!")==false)
    {
      name.focus();
      return false;
    }

    if (validate_required(password1,"Password must be filled out!")==false)
    {
      password1.focus();
      return false;
    }

    if (isPasswordValid("password1","password1Error")==false)
    {
      password1.focus();
      return false;
    }

    if (validate_required(password2,"Retype the password.")==false)
    {
      password2.focus();
      return false;
    }

    if(checkEqualPassword("password1", "password2","password1Error", "password2Error")==false)
    {
      password2.focus();
      return false;
    }

    if (validate_checkbox_required(agree,"You must agree on the Terms & Conditions to continue")==false)
    {
      agree.focus();
      return false;
    }

    password_1.value=hex_md5_update(password1.value, 'password1', 'password_1', 'password1Error');
		password_2.value=hex_md5_update(password2.value, "password2", "password_2", "password2Error");
    }

}


function fb_validate_landing_form(thisform){
  with (thisform){
    if (validate_required(name,"Your name must be filled out!")==false)
    {
      name.focus();
      return false;
    }

    if (validate_required(email,"Email must be filled out!")==false)
    {
      email.focus();
      return false;
    }

    if (isEmailValid(email,"Invalid email address.")==false)
    {
      email.focus();
      return false;
    }

    if (validate_checkbox_required(agree,"You must agree on the Terms & Conditions to continue")==false)
    {
      agree.focus();
      return false;
    }
  }

}

function validate_dev_landing_form(thisform){
  with (thisform){
    if (validate_required(name,"Your name must be filled out!")==false)
    {
      name.focus();
      return false;
    }

    if (validate_required(email,"Email must be filled out!")==false)
    {
      email.focus();
      return false;
    }

    if (isEmailValid(email,"Invalid email address.")==false)
    {
      email.focus();
      return false;
    }

    if (validate_required(password1,"Password must be filled out!")==false)
    {
      password1.focus();
      return false;
    }

    if (isPasswordValid("password1","password1Error")==false)
    {
      password1.focus();
      return false;
    }

    password_1.value=hex_md5_update(password1.value,'password_1');
    pastePassword('password_1','password_2');
    }
}

//add by LA

function validate_email_form(thisform){
  with (thisform){
    if (validate_required(newEmail,"Email must be filled out!")==false)
    {
      newEmail.focus();
      return false;
    }
    if (isEmailValid(newEmail,"Invalid email address.")==false)
    {
      newEmail.focus();
      return false;
    }
  }

}

function validate_advertisePayment_form(thisform, userId){
  with (thisform){
    if (validate_checkbox_required(agree,"You must agree on the Terms & Conditions to continue")==false)
    {
      agree.focus();
      thisform.disabled=false;
      return false;
    }
    }
  saveAdsPayment(userId);
}

// make sure user agree on T&C before continue to make payment from credit card
function validate_cart_form(thisform, userId){
  with (thisform){
    if (validate_checkbox_required(agreeTopUp,"Must agree on T&C to continue")==false)
    {
      agreeTopUp.focus();
      thisform.disabled=false;
      return false;
    }
    }
  savePayment(userId);
}


function validate_topup_form(thisform, userId, cartId, currency, location){
  //var accountType = document.getElementById("desc").value;
  var accountType = document.getElementById("desc2").value;
  var agree = document.getElementById("agreeTopUp");
	var price = document.getElementById("amount3").value;

  if (agree.checked==true){
    var showStatus = function(msgString){
    }

    //var currency = document.getElementById("currency").value;
    //var cartId = document.getElementById("cartId").value;
    PaymentTopup.saveTopUpDetails(userId, price, currency, cartId, "RBS", accountType, location, {callback:showStatus,errorHandler:error});
  }else{
    document.getElementById("agreeTopUpError").innerHTML="Must agree on T&C to continue";
    document.getElementById("agreeTopUp").focus();
    return false;
  }
}

/* Aiwei: validate Paypal top up form before submit
need to have separated form for RBS & Paypal because the fields in the forms are not same */

function validate_paypal_topup_form(thisform, userId, cartId, currency, location, userType){
  var accountType = document.getElementById("accountType3").value;
  var agree = document.getElementById("agreeTopUp");
	var price = document.getElementById("amount1").value;

  if (agree.checked==true){
		if (price>0){
			if (isPrice(document.getElementById("amount1"),"Please enter amount in 12.35 format.")==false){
				document.getElementById("amountPaypal").focus();
				return false;
			}else{
				if (userType=='Developer'){
					if (price>=10){
						return true;
					}else{
						document.getElementById("amountError").innerHTML="Top up amount must be $10.00 or more";
						document.getElementById("amountPaypal").focus();
						return false;
					}
				}else{
					return true;
				}
			}
		}else{
			document.getElementById("amountError").innerHTML="Top up amount must be $10.00 or more";
			document.getElementById("amountPaypal").focus();
			return false;
		}
  }else{
    document.getElementById("agreeTopUpError").innerHTML="Must agree on T&C to continue";
    document.getElementById("agreeTopUp").focus();
    return false;
  }

}

function validate_ipay88_topup_form(userType){
	var accountType = document.getElementById("accountTypeIpay").value;
	var agree = document.getElementById("agreeTopUp");
	var price = document.getElementById("amount2").value;

	if (agree.checked==true){
		if (userType=='Developer'){
			if (price>=10){
				return true;
			}else{
				document.getElementById("amountError").innerHTML="Top up amount must be $10.00 or more";
				document.getElementById("amountPaypal").focus();
				return false;
			}
		}else{
			return true;
		}
	}else{
		document.getElementById("agreeTopUpError").innerHTML="Must agree on T&C to continue";
		document.getElementById("agreeTopUp").focus();
		return false;
	}
}


function validate_ipay88_topup_2_form(userType){
	var accountType = document.getElementById("accountTypeIpay").value;
	var agree = document.getElementById("agreeTopUp");
	var price = document.getElementById("amount2").value;

	if (agree.checked==true){
		if (userType=='Developer'){
			return true;
		}else{
			return true;
		}
	}else{
		document.getElementById("agreeTopUpError").innerHTML="Must agree on T&C to continue";
		document.getElementById("agreeTopUp").focus();
		return false;
	}
}

/*
function validate_paypal_topup_form_2(thisform, userId, cartId, currency){
  var accountType = document.getElementById("accountType3").value;
  var agree = document.getElementById("agreeTopUp");
	var price = document.getElementById("amount2").value;

  if (agree.checked==true){
    return true;
  }else{
    document.getElementById("agreeTopUpError").innerHTML="Must agree on T&C to continue";
    document.getElementById("agreeTopUp").focus();
    return false;
  }

}
*/
function validate_payout_form(thisform){
  with (thisform){

		if (validate_required(threshold,"Threshold must be filled out!")==false){
			threshold.focus();
			
			$('a[rel=psettingsPaypal]').removeClass('tabs-selected');
			$('a[rel=psettingsBank]').removeClass('tabs-selected');
			document.getElementById('psettingsPaypal').style.display = 'none';
			document.getElementById('psettingsBank').style.display = 'none';
			
			$('a[rel=psettingsOverview]').addClass('tabs-selected');
			document.getElementById("psettingsOverview").style.display = 'block';
			
			return false;
		}
		if (isPrice(threshold,"Please enter amount in 12.35 format.")==false){
			threshold.focus();
			$('a[rel=psettingsPaypal]').removeClass('tabs-selected');
			$('a[rel=psettingsBank]').removeClass('tabs-selected');
			document.getElementById('psettingsPaypal').style.display = 'none';
			document.getElementById('psettingsBank').style.display = 'none';
			
			$('a[rel=psettingsOverview]').addClass('tabs-selected');
			document.getElementById("psettingsOverview").style.display = 'block';
			return false;
		}
		if (threshold.value<50){
			document.getElementById("thresholdError").innerHTML = "Threshold has to be US$50 or more";
			threshold.focus();
			$('a[rel=psettingsPaypal]').removeClass('tabs-selected');
			$('a[rel=psettingsBank]').removeClass('tabs-selected');
			document.getElementById('psettingsPaypal').style.display = 'none';
			document.getElementById('psettingsBank').style.display = 'none';
			
			$('a[rel=psettingsOverview]').addClass('tabs-selected');
			document.getElementById("psettingsOverview").style.display = 'block';
			return false;
		}
		
		// for paypal
		if (payoutTypeId.value==2){
			/* to show the selected tab */
			$('a[rel=psettingsOverview]').removeClass('tabs-selected');
			$('a[rel=psettingsBank]').removeClass('tabs-selected');
			document.getElementById('psettingsOverview').style.display = 'none';
			document.getElementById('psettingsBank').style.display = 'none';
			
			$('a[rel=psettingsPaypal]').addClass('tabs-selected');
			document.getElementById("psettingsPaypal").style.display = 'block';
			
			if (validate_required(emailPaypal,"Paypal email must be filled out!")==false)
			{
				emailPaypal.focus();
				return false;
			}
			if (isEmailValid(emailPaypal, "Invald email address.")==false)
			{
				emailPaypal.focus();
				return false;
			}
			if (validate_required(firstNamePaypal,"First name must be filled out!")==false){
				firstNamePaypal.focus();
				return false;
			}
			if (validate_required(lastNamePaypal,"Last name must be filled out!")==false){
				lastNamePaypal.focus();
				return false;
			}
			if (validate_required(addressPaypal,"Address must be filled out!")==false){
				addressPaypal.focus();
				return false;
			}
			if (validate_required(cityPaypal,"City must be filled out!")==false){
				cityPaypal.focus();
				return false;
			}
			if (validate_required(statePaypal,"State must be filled out!")==false)
			{
				statePaypal.focus();
				return false;
			}
			if (validate_required(zipcodePaypal,"Zipcode must be filled out!")==false){
				zipcodePaypal.focus();
				return false;
			}
			if (isZipcodeValid(zipcodePaypal, "Invalid Zipcode.")==false){
				zipcodePaypal.focus();
				return false;
			}
			
			if (validate_required(phonePaypal,"Phone must be filled out!")==false){
				phonePaypal.focus();
				return false;
			}
			if (isPhoneValid(phonePaypal, "Invalid phone format.")==false){
				phonePaypal.focus();
				return false;
			}
			
				
    }else if (payoutTypeId.value==5){	// for TT
			/* to show the selected tab */
			$('a[rel=psettingsOverview]').removeClass('tabs-selected');
			$('a[rel=psettingsPaypal]').removeClass('tabs-selected');
			
			document.getElementById('psettingsOverview').style.display = 'none';
			document.getElementById('psettingsPaypal').style.display = 'none';
			
			$('a[rel=psettingsBank]').addClass('tabs-selected');
			document.getElementById("psettingsBank").style.display = 'block';
			
			
			if (validate_required(firstName,"First name must be filled out!")==false){
				firstName.focus();
				return false;
			}
			if (validate_required(lastName,"Last name must be filled out!")==false){
				lastName.focus();
				return false;
			}
			if (validate_required(address,"Address must be filled out!")==false){
				address.focus();
				return false;
			}
			if (validate_required(city,"City must be filled out!")==false){
				city.focus();
				return false;
			}
			if (validate_required(state,"State must be filled out!")==false)
			{
				state.focus();
				return false;
			}
			if (validate_required(zipcode,"Zipcode must be filled out!")==false){
				zipcode.focus();
				return false;
			}
			if (isZipcodeValid(zipcode, "Invalid Zipcode.")==false){
				zipcode.focus();
				return false;
			}
			if (validate_required(email,"Email must be filled out!")==false){
				email.focus();
				return false;
			}
			if (isEmailValid(email, "Invalid email address.")==false){
				email.focus();
				return false;
			}
			if (validate_required(phone,"Phone must be filled out!")==false){
				phone.focus();
				return false;
			}
			if (isPhoneValid(phone, "Invalid phone format.")==false){
				phone.focus();
				return false;
			}
/*
			if (validate_required(threshold,"Threshold must be filled out!")==false){
				threshold.focus();
				return false;
			}
			if (isPrice(threshold,"Please enter amount in 12.35 format.")==false){
				threshold.focus();
				return false;
			}
			if (threshold.value<50){
				document.getElementById("thresholdError").innerHTML = "Threshold has to be US$50 or more";
				threshold.focus();
				return false;
			}
			*/
      if (validate_required(bankName,"Bank name must be filled out!")==false)
      {
        bankName.focus();
        return false;
      }
      if (validate_required(bankAddress,"Bank Address must be filled out!")==false)
      {
        bankAddress.focus();
        return false;
      }
      if (validate_required(bankCity,"Bank City must be filled out!")==false)
      {
        bankCity.focus();
        return false;
      }
      if (validate_required(bankState,"Bank State must be filled out!")==false)
      {
        bankState.focus();
        return false;
      }
      if (validate_required(bankZipcode,"Bank Zipcode must be filled out!")==false)
      {
        bankZipcode.focus();
        return false;
      }
      if (validate_required(swift,"SWIFT/Clearning code must be filled out!")==false)
      {
        swift.focus();
        return false;
      }
      if (validate_required(accountNo,"Account no/IBAN must be filled out!")==false)
      {
        accountNo.focus();
        return false;
      }
    }
    }
}

function checkNicknameLength(id, status, min, max, type){
  var set1 = document.getElementById(id).value;
  if ((set1.length < min) || (set1.length > max)){
    document.getElementById(status).innerHTML = "<span  class=\"warning bold\"> Use 6 to 32 characters. You may use letters, numbers, and underscores.</span>";
    return false;
  }else{
    document.getElementById(status).innerHTML = "<span  class=\"goodMessage bold\"> "+type+" OK.</span>";
    return true;
  }
}

/* Check if old password and new password are the same */
function checkEqualPassword(ori, confirm, stateError1, stateError2){
  var password = document.getElementById(ori).value;
  var confirmPassword = document.getElementById(confirm).value;
  var message1 = document.getElementById(stateError1);
  var message2 = document.getElementById(stateError2);
  //var greenMessage = document.getElementById(stateOK);
  //message1.innerHTML = "";
  //message2.innerHTML = "";
  //greenMessage.innerHTML = "";

  if (isEmpty(password)){
    message1.innerHTML = " Password is Empty!";
    return false;
  }else if(isEmpty(confirmPassword)){
    message2.innerHTML = " Verify Password is Empty!";
    return false;
  }else{
    if (password==confirmPassword){
      message2.innerHTML = "";
    //greenMessage.innerHTML = ""; //" <img src=\"images/correct.png\"> Passwords are the same";
    }else{
      message2.innerHTML = " Passwords are not the same";
      return false;
    }
  }
  return true;
}


function checkEmail(email1, email2, data){

  var set1 = document.getElementById(email1).value;
  var set2 = document.getElementById(email2).value;

  if (isEmpty(set1) && isEmpty(set2)){
    document.getElementById(data).innerHTML = "<span class=\"warning bold\">Emails are blank.</span>";
    return false;
  }
  if (isEmpty(set2)){
    document.getElementById(data).innerHTML = "<span class=\"warning bold\"> Please type your email again, it's blank now.</span>";
    return false;
  }else{
    var str=document.getElementById(email1).value;
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    if (filter.test(str)){
      document.getElementById(data).innerHTML = "";
      if(set1 != set2){
        document.getElementById(data).innerHTML = "<span class=\"warning bold\"> Emails don't match.</span>";
        return false;
      }else{
        document.getElementById(data).innerHTML = "<span class=\"goodMessage bold\"> Email's OK.</span>";
        return true;
      }
    }else{
      document.getElementById(data).innerHTML = "<span class=\"warning bold\"> Invalid email address.</span>";
      return false;
    }
  }
}



function scrollToBottom(elm_id)
{
  var elm = document.getElementById(elm_id);
  try
  {
    elm.scrollTop = elm.scrollHeight;
  }
  catch(e)
  {
    var f = document.createElement("input");
    if (f.setAttribute) f.setAttribute("type","text")
    if (elm.appendChild) elm.appendChild(f);
    f.style.width = "0px";
    f.style.height = "0px";
    if (f.focus) f.focus();
    if (elm.removeChild) elm.removeChild(f);
  }
}


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document;
  if(d.images){
    if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
    for(i=0; i<a.length; i++)
      if (a[i].indexOf("#")!=0){
        d.MM_p[j]=new Image;
        d.MM_p[j++].src=a[i];
      }
  }
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;
  if(!d) d=document;
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document;
    n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all) x=d.all[n];
  for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n);
  return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;
  document.MM_sr=new Array;
  for(i=0;i<(a.length-2);i+=3)
    if ((x=MM_findObj(a[i]))!=null){
      document.MM_sr[j++]=x;
      if(!x.oSrc) x.oSrc=x.src;
      x.src=a[i+2];
    }
}

function generatePicture(fileTotal, appsVerId, appsId){
  var totalFile = fileTotal.value;
  var text = "";
  for(i=0;i<totalFile;i++){
    text += "<iframe src='apps_upload_image.jsp?appsVerId="+appsVerId+"&appsId="+appsId+"' id='apps_image_"+i+"' name='apps_image_"+i+"' frameborder=0 width='390px' height='150px'></iframe><br>";
  }
  document.getElementById("pictureContainer").innerHTML = text;

}



/*
usage to show hide layer and position in the middle of a screen
This JS takes two layers one to be showed(with x,y dim) and the other to be hide.
In addition, the showLayer method sets the position of the showed layer in the middle of the browser
Finally, the background layer is disabled till the close image will be pressed
this version is done in such away to be re-used.
*/
/*
function getBrowserHeight() {
		var intH = 0;
		var intW = 0;

		if(typeof window.innerWidth  == 'number' ) {
			 intH = window.innerHeight;
			 intW = window.innerWidth;
		}
		else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
				intH = document.documentElement.clientHeight;
				intW = document.documentElement.clientWidth;
		}
		else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
				intH = document.body.clientHeight;
				intW = document.body.clientWidth;
		}

		return { width: parseInt(intW), height: parseInt(intH) };
}

function setLayerPosition(x,y) {
		var shadow = document.getElementById("shadow");
		var question = document.getElementById("question");
if(shadow==null) return;//fix the call from others pages that don't has shadow layer
		var bws = getBrowserHeight();

		shadow.style.width = bws.width + "px";
	 // shadow.style.height = bws.height + "px"; //to shadow all the page not only browser document.height
		 shadow.style.height =1248+ "px";

		question.style.left = (parseInt(bws.width ) -x)/ 2+ "px";
		question.style.top =  (parseInt(bws.height ) -y)/ 2+ "px";

		shadow = null;
		question = null;
}

function showLayer(x,y) {
		setLayerPosition(x,y);

		var shadow = document.getElementById("shadow");
		var question = document.getElementById("question");

		shadow.style.display = "block";
		question.style.display = "block";

		shadow = null;
		question = null;
}

function hideLayer() {
		var shadow = document.getElementById("shadow");
		var question = document.getElementById("question");

		shadow.style.display = "none";
		question.style.display = "none";

		shadow = null;
		question = null;
}

window.onresize = setLayerPosition;
*/

// to highlight the selected tab
function highlight(id){
  document.getElementById(id).className = "active";
}

function validate_newapp_form(thisform){
  with (thisform){
    if (validate_required(categoryId,"Please select a category!")==false)
    {
      categoryId.focus();
      return false;
    }
    if (validate_required(name,"App Name must be filled out!")==false)
    {
      name.focus();
      return false;
    }
    if (validate_required(title,"App Title must be filled out!")==false)
    {
      title.focus();
      return false;
    }
    if (validate_required(description,"App Description must be filled out!")==false)
    {
      description.focus();
      return false;
    }
		if (validate_required(keywords,"Keywords must be filled out!")==false)
    {
      keywords.focus();
      return false;
    }
    if (validate_required(version,"Version must be filled out!")==false)
    {
      version.focus();
      return false;
    }
    /*if (validate_required(credits,"Credits must be filled out!")==false)
    {
      credits.focus();
      return false;
    }
		if (isNumeric(credits,"Credits must be numbers!")==false){
      credits.focus();
      return false;
    }*/
    if (validate_required(price,"Price must be filled out!")==false)
		  {price.focus();return false;}
		if (isPrice(price,"Please enter amount in 12.35 format.")==false)
		  {price.focus();return false;}

   /* var platformCheck = document.getElementsByName("platform");//document.applicationNewForm.platform;
    var platformHasChecked = false;
    for (var i=0;i<platformCheck.length;i++){
      if (platformCheck[i].checked){
        platformHasChecked = true;
        break;
      }
    }
		*/
		var platformCheck = document.getElementById("platform");
    if (platformCheck.value==0){
      document.getElementById("platformError").innerHTML = "At least 1 platform must be selected";
      return false;
    }

    var osCheck = document.getElementsByName('os_name');
    var osHasChecked = false;
    for (var j=0;j<osCheck.length;j++){
      if (osCheck[j].checked){
        osHasChecked = true;
        break;
      }
    }
    if (!osHasChecked){
      document.getElementById("osNameError").innerHTML = "<span class='warning bold'>At least 1 operating system must be selected</span>";
      return false;
    }

    }
}

function validate_newVersion_form(thisform){

  with (thisform){
    if (validate_required(version,"Version must be filled out!")==false)
    {
      version.focus();
      return false;
    }
    if (validate_required(price,"Price must be filled out!")==false)
    {
      price.focus();
      return false;
    }
    if (isPrice(price,"Please enter amount in 12.35 format.")==false)
    {
      price.focus();
      return false;
    }
		if (publishSiteWW != null && publishSiteWW.checked){
			if (validate_required(yen,"Price must be filled out!")==false)
				{yen.focus();return false;}
			if (isNumeric(yen,"Credits must be numbers!")==false){
				yen.focus();return false;
			}
		}
    //make sure at least 1 platofmr and 1 OS is selected
		var platformCheck = document.getElementById("platform");
    if (platformCheck.value==0){
      document.getElementById("platformError").innerHTML = "At least 1 platform must be selected";
      return false;
    }

    /*var platformCheck = document.getElementsByName("platform");//document.applicationNewForm.platform;
    var platformHasChecked = false;
    for (var i=0;i<platformCheck.length;i++){
      if (platformCheck[i].checked){
        platformHasChecked = true;
        break;
      }
    }
    if (!platformHasChecked){
      document.getElementById("platformError").innerHTML = "<span class='warning bold'>At least 1 platform must be selected</span>";
      return false;
    }
		*/
    var osCheck = document.getElementsByName('os_name');
    var osHasChecked = false;
    for (var j=0;j<osCheck.length;j++){
      if (osCheck[j].checked){
        osHasChecked = true;
        break;
      }
    }
    if (!osHasChecked){
      document.getElementById("osNameError").innerHTML = "<span class='warning bold'>At least 1 operating system must be selected</span>";
      return false;
    }

    }
}

//Added by Boon sheng for device selection validation
function validate_setPhoneForm_form(thisform, selectValue){
  with (thisform){
    if (validate_required(setModel,"Please select your phone brand and Model!")==false){
      setModel.focus();
      return false;
    } else if(validate_required(setPhone,"Please select your phone brand and Model!")==false){
			setPhone.focus();
      return false;
    }

  }
	var index = document.getElementById(selectValue).selectedIndex;
	var phoneId= document.getElementById(selectValue).value;
	var showStatus = function(msgString){
		if (msgString.length>0){
			var result = msgString[0];
			document.getElementById("message1").innerHTML = document.getElementById(selectValue).options[index].text;
			document.getElementById("message2").innerHTML = result.name;
			document.getElementById("message3").innerHTML = result.name;
		}
		hideLayer("phoneBox");
		showLayer("messagePublish");
	}
	var userId = document.getElementById("phoneUserId").value;
	Platform.findByPhoneModelIdAjax(phoneId, userId, {callback:showStatus, errorHandler:error});
}


function validate_newphones_form(thisform){
  with (thisform){
    //make sure at least 1 platofmr and 1 OS is selected
   /* var platformCheck = document.getElementsByName("platform");//document.applicationNewForm.platform;
    var platformHasChecked = false;
    for (var i=0;i<platformCheck.length;i++){
      if (platformCheck[i].checked){
        platformHasChecked = true;
        break;
      }
    }
    if (!platformHasChecked){
      document.getElementById("platformError").innerHTML = "<span class='warning bold'>At least 1 platform must be selected</span>";
      return false;
    }
		*/
		var platformCheck = document.getElementById("platform");
    if (platformCheck.value==0){
      document.getElementById("platformError").innerHTML = "At least 1 platform must be selected";
      return false;
    }
    var osCheck = document.getElementsByName('os_name');
    var osHasChecked = false;
    for (var j=0;j<osCheck.length;j++){
      if (osCheck[j].checked){
        osHasChecked = true;
        break;
      }
    }
    if (!osHasChecked){
      document.getElementById("osNameError").innerHTML = "<span class='warning bold'>At least 1 operating system must be selected</span>";
      return false;
    }

    }
}

function checkPhone(platformId, alerttxt, appsVerId, userId, clickTracer, referredUrl, location, confirmMessage, file, price){
  if (userId>0){
    if (platformId== 0){
      document.getElementById("platformIdError").innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
    //return false;
    }else{
      //saveCart(appsVerId, userId, platform.value, clickTracer);
      if (confirmDelete(confirmMessage)){
        //payFromAccount(appsVerId, userId, platform.value, clickTracer, referredUrl);
        if (userId==0){
          document.getElementById("addCart_"+appsVerId).innerHTML = "<a href='javascript:showLayer(\"loginBox\")'>Login</a> to buy app";
        }else{
          var showStatus = function(msgString){
            if (msgString.length>0){
              if (msgString[0]['status']=="done"){
								if (msgString[0]['credit']>0){
                  document.getElementById("addCart_"+appsVerId).innerHTML = "";
									document.getElementById("addCart_"+appsVerId).innerHTML = "<img src='images/ok.png'> "+(msgString[0]['credit']*100).toFixed(2)+" credits has been deducted from your account. Click <a href=\"javascript:void(0)\" onclick=\"javascript:window.open('"+file+"','Download');\" class='link_title'>here</a> if download not started automatically or login to http://www.mobileapps.com using your device to download this app.";
                  window.open(file,'Download');
								}else{
                  document.getElementById("addCart_"+appsVerId).innerHTML = "";
									document.getElementById("addCart_"+appsVerId).innerHTML = "<img src='images/ok.png'> Click <a href=\"javascript:void(0)\" onclick=\"javascript:window.open('"+file+"','Download');\" class='link_title'>here</a> if download not started automatically or login to http://www.mobileapps.com using your device to download this app.";
                  window.open(file,'Download');
								}
              }else if (msgString[0]['status']=="credit"){
                document.getElementById("addCart_"+appsVerId).innerHTML = "Sorry, not enough credit in your account. Please <a href='home_topup.jsp'>top up your account</a>";
              }else if (msgString[0]['status']=="account"){
                document.getElementById("addCart_"+appsVerId).innerHTML = "Sorry, not enough credit in your account. Please <a href='home_topup.jsp'>top up your account</a>";
              }
            }
          }
					document.getElementById("addCart_"+appsVerId).innerHTML = "<div style='float:left;'><img src='images/loading.gif'/></div><div style='float:left;padding-left:5px;'> loading...</div><br>";
          Account.saveAppPayFromAccountDetails(appsVerId, userId, platformId, clickTracer, referredUrl, location, {callback:showStatus, errorHandler:error});
        }
      }
    }
  }else{
    if(price>0)
      document.getElementById("addCart_"+appsVerId).innerHTML = "<a href='javascript:showLayer(\"loginBox\")'>Login</a> to buy app";
    else
      //showLayer("downloadBox");
	  window.open(file,'Download');
  }
}

function checkPhone2(platId, alerttxt, appsVerId, userId, clickTracer, referredUrl){
  if (userId>0){
    if (platId == 0){
      document.getElementById(id+"Error").innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
    //return false;
    }else{
      //saveCart(appsVerId, userId, platform.value, clickTracer);
      if (confirmDelete("Confirm Buy this App?")){
        //payFromAccount(appsVerId, userId, platId, clickTracer, referredUrl);

        if (userId==0){
          document.getElementById("addCart_"+appsVerId).innerHTML = "<a href='javascript:showLayer(\"loginBox\")'>Login</a> to buy app";
        }else{
          var showStatus = function(msgString){
            if (msgString.length>0){
              if (msgString[0]['status']=="done"){
                document.getElementById("addCart_"+appsVerId).innerHTML = "<img src='images/ok.png'> $xxx has been deducted from your account. Please use this link - http://m.mobileapps.com - to download your app";
              }
            }
          }
          Account.saveAppPayFromAccountDetails(appsVerId, userId, platform.value, clickTracer, referredUrl,{callback:showStatus,errorHandler:error});
        }

      }
    }
  }else{
    document.getElementById("addCart_"+appsVerId).innerHTML = "<a href='javascript:showLayer(\"loginBox\")'>Login</a> to buy app";
  }
}

function checkPhoneReview(id, alerttxt, appsVerId, userId){
  var platform = document.getElementById(id);
  if (platform.value == 0){
    document.getElementById(id+"Error").innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
    return false;
  }else{
    alert("This page for review only.");
    return false;
  }
}

function checkPhoneIphone(id, alerttxt, url, appsId, appsVerId, userId){
  var platform = document.getElementById(id);
  if (platform.value == 0){
    document.getElementById(id+"Error").innerHTML = "<span class=\"warning bold\"> "+alerttxt+"</span>";
  //return false;
  }else{
    downloadFile(appsId, appsVerId, userId, '0', platform.value);
    window.open(url,'mywindow','width=800,height=500')
  }
}


function showTab(id){
  //var allTabs=["callDescription","callScreens","callReviews", "callSupport", "callPhones", "callOldVersion"];
  //var allTabsId=["description","screens","reviews", "support", "phones", "oldVersion"];
  var allTabs=["callDescription","callVideo","callReviews", "callPhones", "callOldVersion"];
  var allTabsId=["description","video","reviews", "phones", "oldVersion"];
  for (i=0;i<allTabs.length;i++){
    if (id==allTabsId[i]){
      document.getElementById(allTabs[i]).className = "selected";
      showLayer(allTabsId[i]);
    }else{
      document.getElementById(allTabs[i]).className = "unselected";
      hideLayer(allTabsId[i]);
    }
  }
}

function showUserHome(id){
  var allTabs=["myHomePurchased","myHomeDownload", "myHomeHistoryTopUp"];
  var allTabsId=["home_1","home_3", "home_5"];
  for (i=0;i<allTabs.length;i++){
    if (id==allTabs[i]){
      document.getElementById(allTabsId[i]).className="selected";
      showLayerLayer(allTabs[i]);
    }else{
      document.getElementById(allTabsId[i]).className="unselected";
      hideLayer(allTabs[i]);
    }
  }
}

// change apps details page title to reflect the app's name
function changeTitle(title) {
  document.title = title + " - MobileApps.com";
}

function liveView(from,toWhere){
  document.getElementById(toWhere).innerHTML = document.getElementById(from).value;
}

function limitText(limitField, id, limitNum) {
  if (limitField.value.length >= limitNum+1) {
    limitField.value = limitField.value.substring(0, limitNum);
    return false;
  } else {
    var text = limitNum - limitField.value.length;
    document.getElementById(id).innerHTML = "<span> "+text+"</span>";
    return false;
  }
}

// change the meta tag on the product profile page
// added by Boon Sheng
function changeMetaTag(mname,mcontent) {
  var cnt =0;
  if(!mcontent == "" || !mcontent == null)
  {
    metatags = document.getElementsByTagName("meta");
    // Iterate through the array, listing them all
    for (var cnt = 0; cnt < metatags.length; cnt++)
    {
      // Update the meta tag
      if (metatags[cnt].getAttribute("name") == mname)	{
        metatags[cnt].setAttribute("content", mcontent);
      }
    }
  }
}

function validate_android_app_search_form(thisform){
  with (thisform){
    if (validate_required(developer_name,"Developer Name must be filled out!")==false)
    {
      developer_name.focus();
      return false;
    }

    }
}

function validate_android_app_import_form(thisform){
  with (thisform){

    var importAppsId = document.getElementsByName("importAppsId");
    var importAppsIdHasChecked = false;
    if (importAppsId != null && importAppsId.length > 0) {
      for (var i=0;i< importAppsId.length;i++){

        if (importAppsId[i].checked){
          importAppsIdHasChecked = true;
          showLayer("agreementMessage");
          break;
        }
      }
    } else {
      if (importAppsId.checked){
        importAppsIdHasChecked = true;
        showLayer("agreementMessage");
      }
    }

    if (!importAppsIdHasChecked){
      document.getElementById("importAppsIdError").innerHTML = "<span class='warning bold'>At least 1 app must be selected to import</span>";
      return false;
    } else {
      return true;
    }

    }
}

function validate_iphone_app_search_form(thisform){
  with (thisform){
    if (validate_required(developer_name,"Developer Name must be filled out!")==false)
    {
      developer_name.focus();
      return false;
    }

    }
}

function validate_iphone_app_import_form(thisform){
  with (thisform){

    var importAppsId = document.getElementsByName("importAppsId");
    var importAppsIdHasChecked = false;
    if (importAppsId != null && importAppsId.length > 0) {
      for (var i=0;i< importAppsId.length;i++){

        if (importAppsId[i].checked){
          importAppsIdHasChecked = true;
          showLayer("agreementMessage");
          break;
        }
      }
    } else {
      if (importAppsId.checked){
        importAppsIdHasChecked = true;
        showLayer("agreementMessage");
      }
    }

    if (!importAppsIdHasChecked){
      document.getElementById("importAppsIdError").innerHTML = "<span class='warning bold'>At least 1 app must be selected to import</span>";
      return false;
    } else {
      return true;
    }

    }
}


function validate_editapp_form(thisform){
  with (thisform){
    if (validate_required(name,"App Name must be filled out!")==false)
    {
      name.focus();
      return false;
    }
    if (validate_required(title,"App Title must be filled out!")==false)
    {
      title.focus();
      return false;
    }
    if (validate_required(description,"App Description must be filled out!")==false)
    {
      description.focus();
      return false;
    }
		if (validate_required(keywords,"Keywords must be filled out!")==false)
    {
      keywords.focus();
      return false;
    }
    if (validate_required(version,"Version must be filled out!")==false)
    {
      version.focus();
      return false;
    }
    /*if (validate_required(credits,"Credits must be filled out!")==false)
    {
      credits.focus();
      return false;
    }

		if (isNumeric(credits,"Credits must be numbers!")==false){
      credits.focus();
      return false;
    }*/
    if (validate_required(price,"Price must be filled out!")==false)
		  {price.focus();return false;}
		if (isPrice(price,"Please enter amount in 12.35 format.")==false)
		  {price.focus();return false;}
		if (publishSiteWW != null && publishSiteWW.checked){
			if (validate_required(yen,"Price must be filled out!")==false)
				{yen.focus();return false;}
			if (isNumeric(yen,"Credits must be numbers!")==false){
				yen.focus();return false;
			}
		}
    /*var platformCheck = document.getElementsByName("platform");//document.applicationNewForm.platform;
		var platformHasChecked = false;
		for (var i=0;i<platformCheck.length;i++){
			if (platformCheck[i].checked){
				platformHasChecked = true;
				break;
			}
		}
		if (!platformHasChecked){
			document.getElementById("platformError").innerHTML = "<span class='warning bold'>At least 1 platform must be selected</span>";
			return false;
		}

		var osCheck = document.getElementsByName('os_name');
		var osHasChecked = false;
		for (var j=0;j<osCheck.length;j++){
			if (osCheck[j].checked){
				osHasChecked = true;
				break;
			}
		}
		if (!osHasChecked){
			document.getElementById("osNameError").innerHTML = "<span class='warning bold'>At least 1 operating system must be selected</span>";
			return false;
		}
		*/
    }
}

function validate_import_agreement(thisform){

  with (thisform){
    var checkAgreement = document.getElementsByName("checkAgreement");
    for(i=0;i<checkAgreement.length;i++){
      if (checkAgreement[i].checked){
        return true;
      }
      else{
        document.getElementById("checkAgreementError").innerHTML = "<span class='warning bold'>To import, you must agree with the terms and conditions by clicking the check box above.   </span>";
        return false;
      }
    }
    }
}


/*
calculate total price when rebid, show error if price or total impression are not entered
*/
/*function calculateRebid(balance, currentPrice, ipvoId, userId){
	var newPrice = document.getElementById("newPrice_"+ipvoId+"_"+userId);

	if (isPrice(newPrice,"Please enter amount in 12.35 format")==false)
		{newPrice.focus();return false;}

	if (newPrice.value>0 && newPrice.value>currentPrice){
		var newTotal = (newPrice.value)*balance/1000;
		var newTotalToPay = (newPrice.value-currentPrice)*balance/1000;
		document.getElementById("newTotal_"+ipvoId+"_"+userId).innerHTML = newTotal.toFixed(2);
		document.getElementById("newTotalToPay_"+ipvoId+"_"+userId).innerHTML = newTotalToPay.toFixed(2);
	}else{
		if (newPrice.value<=0){
			errorMessage = "New Price must be more than US$0.10";
			document.getElementById("newPrice_"+ipvoId+"_"+userId+"Error").innerHTML = errorMessage;
			return false;
		}
		if (newPrice.value<=currentPrice){
			errorMessage = "New Price must be more than current price";
			document.getElementById("newPrice_"+ipvoId+"_"+userId+"Error").innerHTML = errorMessage;
			return false;
		}
	}

}
*/

/*
calculate total price when bid, show error if price or total impression are not entered
*/

function calculate(type, errorId){
  var price = document.getElementById("pricePerThousand").value;
  var totalImp = document.getElementById("noOfImpression").value;

  if (price>0 && totalImp>0){
    if (type == "update"){
      var originalPrice = document.getElementById("originalPricePerThousand").value;
      //if ((price*(totalImp/1000)) >= originalPrice){
        document.getElementById("totalPrice").innerHTML = "$ "+(Math.floor(((price*totalImp)/1000)*100)/100).toFixed(2);
				if ((Math.floor(((price*totalImp)/1000)*100)/100).toFixed(2)==0.00){
					document.getElementById(errorId).innerHTML = "New price/impression is too low, please enter a higher price or impressions";
					return false;
				}
      /*}else{
        document.getElementById(errorId).innerHTML = "New price must be more than original price";
        return false;
      }*/
    }else{
      document.getElementById("totalPrice").innerHTML = "$ "+(Math.floor((price*totalImp)*100)/100).toFixed(2);
    }

  }else{
    if (!isEmpty(price) && price==0){
      //alert("how to calculate 0? idiot");
      document.getElementById(errorId).innerHTML = "Price must be more than 0";
      return false;
    }
    if (!isEmpty(totalImp) && totalImp==0){
      document.getElementById(errorId).innerHTML = "No of impression must be more than original price";
      return false;
    }
  }
}

function calculateShortCut(id, type, errorId, errorId2){
  var price = document.getElementById("popUpPerThousand_"+id).value;
  var totalImp = document.getElementById("popUpImpressions_"+id).value;
	document.getElementById(errorId).innerHTML = "";
	document.getElementById(errorId2).innerHTML = "";
  if (price>0 && totalImp>0){
    if (type == "update"){
      var originalPrice = document.getElementById("originalPricePerThousand").value;
      //if ((price*(totalImp/1000)) >= originalPrice){
			document.getElementById("popUpTotalPrice_"+id).innerHTML = "$"+(Math.floor((price*totalImp)*100)/100).toFixed(2);
      /*}else{
        document.getElementById(errorId).innerHTML = "New price must be more than original price";
        return false;
      }*/
    }else{
      document.getElementById("popUpTotalPrice_"+id).innerHTML = " $ "+(Math.floor((price*totalImp)*100)/100).toFixed(2);
    }

  }else{
    if (isEmpty(price) || price==0){
      document.getElementById(errorId).innerHTML = "Price must be more than 0";
      return false;
    }
    if (isEmpty(totalImp) || totalImp==0){
      document.getElementById(errorId2).innerHTML = "Impression must be more 0";
      return false;
    }
  }
}

function clearBox(id){
	document.getElementById("popUpPerThousand_"+id+"Error").innerHTML = "";
	document.getElementById("popUpImpressions_"+id+"Error").innerHTML = "";
	document.getElementById("popUpPerThousand_"+id+"Error").innerHTML = "";
}

/*
Aiwei : validate new campaign
*/
function validate_newCamp_form(thisform){
  with (thisform){
    if (validate_required(adsName,"Ad Name must be filled out!")==false)
    {
      adsName.focus();
      return false;
    }
		if (validate_required(appsVersionId,"An app must be selected!")==false)
    {
      appsVersionId.focus();
      return false;
    }
    if (validate_required(dailyBudget,"Daily Budget must be filled out!")==false)
    {
      dailyBudget.focus();
      return false;
    }
    if (isPrice(dailyBudget,"Please enter daily budget in 12.35 format")==false)
    {
      dailyBudget.focus();
      return false;
    }

		if (dailyBudget.value<=0){
      document.getElementById("dailyBudgetError").innerHTML = "<span class='bold warning'>Daily budget has to be more than $0.00</span>";
      dailyBudget.focus();
      return false;
    }

    if (validate_required(countryCode,"At least 1 country must be selected!")==false)
    {
      countryCode.focus();
      return false;
    }
    if (validate_required(scheduleStart,"Start date must be filled out!")==false)
    {
      scheduleStart.focus();
      return false;
    }
    if (validate_required(scheduleStop,"End must be filled out!")==false)
    {
      scheduleStop.focus();
      return false;
    }

		var startDate = new Date(scheduleStart.value.substring(0, 4) + '/' + scheduleStart.value.substring(5, 7) + '/' + scheduleStart.value.substring(8, 10));
		var endDate = new Date(scheduleStop.value.substring(0, 4) + '/' + scheduleStop.value.substring(5, 7) + '/' + scheduleStop.value.substring(8, 10));
		if (startDate > endDate) {
			document.getElementById("scheduleStopError").innerHTML = "Start date cannot be later than end date";
			return false;
    }

  }
}


/*
Aiwei : validate new ad
*/
function validate_newAd_form(thisform){
  with (thisform){
    if (validate_required(adsName,"Ad Name must be filled out!")==false)
    {
      adsName.focus();
      return false;
    }
    if (validate_required(adsTitle,"Ad Title must be filled out!")==false)
    {
      adsTitle.focus();
      return false;
    }
    if (validate_required(adsDescription,"Ad Description must be filled out!")==false)
    {
      adsDescription.focus();
      return false;
    }
		if (premiumAd.checked){
			if (validate_required(premiumExtraChar,"Extra 100 characters for premium ad must be filled out!")==false)
			{
				document.getElementById("premiumCharacter").style.display = "block";
				premiumExtraChar.focus();
				return false;
			}
		}
    }
}

/*
	Aiwei : validate per thousand price and total impression before add to cart.
	new per thousand price must be more than the previous price.
*/
function validate_addCart(){

  /*if ($("originalPricePerThousand").value!=null){
    if (($("pricePerThousand").value*($("noOfImpression").value/1000)) <= $("originalPricePerThousand").value){
      document.getElementById("totalError").innerHTML = "<span class=\"warning bold\"> Must be more than original price</span>";
      document.getElementById("pricePerThousandError").focus();
      return false;
    }
  }*/
  if ($("pricePerThousand").value<=0){
    $("pricePerThousandError").innerHTML = "Must be more than 0";
    $("pricePerThousand").focus();
    return false;
  }
  if (validate_required($("pricePerThousand"),"Price per thousand must be filled out!")==false)
  {
    $("pricePerThousand").focus();
    return false;
  }
  if (isPrice($("pricePerThousand"),"Please enter per thousand price in 12.35 format")==false)
  {
    $("pricePerThousand").focus();
    return false;
  }
  if ($("noOfImpression").value<=0){
    $("noOfImpressionError").innerHTML = "Must be more than 0";
    $("noOfImpression").focus();
    return false;
  }
  if (validate_required($("noOfImpression"),"No of Imp must be filled out!")==false)
  {
    $("noOfImpression").focus();
    return false;
  }
  if (isNumeric($("noOfImpression"),"Please enter total impression in number.")==false)
  {
    $("noOfImpression").focus();
    return false;
  }
}


function validate_addCart_shortCut(id){
  if (validate_required($("popUpPerThousand_"+id),"Price per thousand must be filled out!")==false)
  {
    $("popUpPerThousand_"+id).focus();
    return false;
  }
  if (isPrice($("popUpPerThousand_"+id),"Please enter per thousand price in 12.35 format")==false)
  {
    $("popUpPerThousand_"+id).focus();
    return false;
  }
  if (validate_required($("popUpImpressions_"+id),"No of Imp must be filled out!")==false)
  {
    $("popUpImpressions_"+id).focus();
    return false;
  }
  if (isNumeric($("popUpImpressions_"+id),"Please enter total impression in number.")==false)
  {
    $("popUpImpressions_"+id).focus();
    return false;
  }
}
/*
Aiwei : validate search platform/category/country box at left in campaign's select publishers
only for campaign_choose.jsp and campaign_add_placement.jsp
*/
function validate_search_form(field){
  with (field){
    var platformChecked = 0;
    var countryChecked = 0;
    var categoryChecked = 0;

    for (counter = 0; counter < platformSearch.length; counter++){
      if (platformSearch[counter].checked){
        platformChecked += 1;
      }
    }
    for (counter = 0; counter < countrySearch.length; counter++){
      if (countrySearch[counter].checked){
        countryChecked += 1;
      }
    }
    for (counter = 0; counter < categorySearch.length; counter++){
      if (categorySearch[counter].checked){
        categoryChecked += 1;
      }
    }

    /* show error if at least 1 checkbox is not checked*/
    if (platformChecked==0){
      document.getElementById("searchError").innerHTML = "Select at least 1 Platform";
      return false;
    }
    if (countryChecked==0){
      document.getElementById("searchError").innerHTML = "Select at least 1 Country";
      return false;
    }
    if (categoryChecked==0){
      document.getElementById("searchError").innerHTML = "Select at least 1 Category";
      return false;
    }
    }
}

// check search keyword - return false if the keyword is empty
function validate_search(thisform){
  with (thisform){

    if (isEmpty(keyword.value)){
      keyword.focus();
      return false;
    }
  }
}

/*
Aiwei:
http://madrobby.github.com/scriptaculous/combination-effects-demo/
function to generate animated layer , using scriptaculous
*/
function ScrollLayer(id, dura){
  new Effect.ScrollTo(id, {
    duration:dura
  });
  return false;
}

function AppearLayer(id, dura){
  // blind , slide, appear
  new Effect.toggle(id, 'blind',  {
    duration: dura
  });
  return false;
}

function GrowLayer(id,dura){
  new Effect.Grow(id, {
    duration:dura
  });
  return false;
}

function subStringWork(work, charOfLine, line){
  var result = new Array();
  result[0] = false;
  work = work.replace(/ \*/g, " ");
  work = work.replace(/< /g, "<");
  work = work.replace(/ >/g, ">");
  work = work.replace(/ \//g, "/");
  work = work.replace(/R>/g, "r/>");
  work = work.replace(/r>/g, "r/>");
  work = work.replace(/R\/>/g, "r/>");
  work = work.replace(/<B/g, "<b");
  var splitWork = work.split("<br/>");

  var number = 0;
  for ( var w in splitWork) {
    number++;
    if (splitWork[w].length > charOfLine) {
      var t = splitWork[w].length / charOfLine;
      number += t;
    }
    subWord = splitWork[w];
    if (number > line) {
      number = number - line - 1;
      if (number > 1) {
        number = number * charOfLine;
        subWord = subWord.substring(0, (subWord.length - number));
      }
      result[0] = "true";
      var m = 0;
      if (subWord.length > charOfLine) {
        m = subWord.length % charOfLine;
        subWord = subWord.substring(0, subWord.length - m);
      }
      subWord = subWord + " &hellip; ";
      if (result[1]==null||result[1]=="") {
        result[1] = subWord;
      } else {
        result[1] += "<br/>" + subWord;
      }
      break;
    }
    if (result[1]==null||result[1]=="") {
      result[1] = subWord;
    } else {
      result[1] += "<br/>" + subWord;
    }
  }
  return result;
}

function displayPayNowButton(id1,id2){
  if(document.getElementById(id1).checked){
    showLayer("paymentLogo1");
    showLayer("paymentForm1");
    hideLayer("paymentLogo2");
    hideLayer("paymentForm2");
    showLayer("rbsAmount");
    hideLayer("paypalAmount");
    copyTo(document.getElementById("amountRbs").value, "amount3");
  } else if (document.getElementById(id2).checked) {
    hideLayer("paymentLogo1");
    hideLayer("paymentForm1");
    showLayer("paymentLogo2");
    showLayer("paymentForm2");
    showLayer("paypalAmount");
    hideLayer("rbsAmount");
    copyTo(document.getElementById("amountPaypal").value, "amount2");
  }

}

function selectApps(id,loop) {
  if(loop>0){
    for(var i = 0 ; i<loop;i++){
      if( document.getElementById("apps_"+i).style.boxShadow != ""){
        document.getElementById("apps_"+i).style.boxShadow  ="";
        document.getElementById("apps_"+i).style.backgroundColor ="";
      }
    }
    document.getElementById("apps_"+id).style.boxShadow  ="0 0 4px #999999";
    document.getElementById("apps_"+id).style.backgroundColor ="#DFDFDF";
  }
}

function changeClassName(id){
  if(id==null||id==""){
    id = "Featured";
  } else if( id == "Popular Today" || id == "Popular Yesterday"|| id == "Popular this Week"|| id == "Popular Last Week"|| id == "Popular this Month"|| id == "All Time Popular"){
    document.getElementById("Popular").className = "selected";
  }
  document.getElementById(id).className = "selected";
}

if(!Array.indexOf){
	  Array.prototype.indexOf = function(obj){
		  for(var i=0; i<this.length; i++){
			  if(this[i]==obj){
				  return i;
			  }
		  }
		  return -1;
	  }
  }


function validateDateRange1(startDateElement, endDateElement){

	var startDate = new Date(startDateElement.value.substring(0, 4) + '/' + startDateElement.value.substring(5, 7) + '/' + startDateElement.value.substring(8, 10));
	var endDate = new Date(endDateElement.value.substring(0, 4) + '/' + endDateElement.value.substring(5, 7) + '/' + endDateElement.value.substring(8, 10));

	if (startDate > endDate) {
		document.getElementById("scheduleStopError").innerHTML = "Start date cannot be later than end date";
		return false;
	}
}

function selectPremiumAd(id){
	premiumAd = document.getElementById("premiumAd");
	if (premiumAd.checked){
		document.getElementById("premiumExtraChar").disabled = false;
	}else{
		document.getElementById("premiumExtraChar").disabled = true;
	}
}

function checkStatus(){
	var action = document.getElementById("bulkAction").value;
	if (action== "duplicate"){
		message = "Duplicate data?";
	}else if (action== "archive"){
		message = "Archive? All pub will be in archive";
	}
	return confirm(message);
}

function clearErrorMsg(id){
  document.getElementById(id).innerHTML = "";
}

// ui controls

(function($){

  $(document).ready(function(){
  /*
   *	tooltip
   *
   */
	isTooltipActive = 0;
	tooltipTimer = '';
	uiTooltip = $('.ui-tooltip');
	if (uiTooltip.length>0){
	  uiTooltip.live('mouseover',function(e){
			  var self = $(this);
			  var a = $('#jui-tooltip');
			  var template = "<div id=\"jui-tooltip\"><div class=\"jui-tooltip-frame\"><h3></h3><p></p></div><div class=\"jui-tooltip-arrow\"></div></div>";
			  if (a.length < 1){
				  $('body').append(template);
				  a = $('#jui-tooltip');
			  }

			  // apply data to tooltip
			  a.find('.jui-tooltip-frame > h3').html(""+(self.data('title')||""));
			  a.find('.jui-tooltip-frame > p').html(""+(self.data('message')||""));

			   if ($.browser.msie){
					a.find('.jui-tooltip-frame').css('min-width','200px');
				}
			  // position tooltip
			  if (isTooltipActive===0){

				  tooltipTimer = setTimeout( function(){
				  var x = e.pageX;
				  var y = e.pageY;

				  a.css({
					'display':'block','opacity' : 0
						}).css({
							'top' : y - (a[0].clientHeight+10),
							'left' : x - (a[0].clientWidth/2) //+ (self.clientWidth/2) //uncomment to position over center of element,

						}).animate({
							'top' : y - a[0].clientHeight -10,
							'opacity': 1
						},200);

				  isTooltipActive = 1;
				  }, 300);
			  }
		  }).live('mouseout',function(){
			  var a = $('#jui-tooltip');
			  isTooltipActive = 0;
			  clearTimeout(tooltipTimer);
			  $(a).stop().animate({
					  'opacity' : 0
				  },200,function(){this.style.display = 'none';});

		  });
	}


	/*
	 *	jsLabelOverlay
	 *  --------------
	 *  adds inline labels to input text boxes and textareas.
	 *
	 *	define in parent container like so, label must be within same container as control:
	 *
	 *	<td class="jsLabelOverlay">
	 *		<label for="post_city">City</label>
	 * 		<input type=text name='city' class="span3" id='post_city' value='<%=uvo.city%>'/>
	 *	</td>
	 *
	 */
	var jsLabelOverlay = $('.jsLabelOverlay input[type=text], .jsLabelOverlay textarea');

	for (var i=0;i<jsLabelOverlay.length;i++){
		$(jsLabelOverlay[i]).prev("label").css("display",(jsLabelOverlay[i].value === "" ? "block":"none") );
	}

	jsLabelOverlay.keydown(function(){
		$(this).prev("label").hide();
	}).blur(function(){
		if (isEmpty(this.value)){
			this.value='';
			$(this).prev("label").show();
		}else{
			$(this).prev("label").hide();
		}
	});

	/*
	 *	tabs
	 *
	 */
	$('.tabs').find('.tabs-nav').delegate("a","click",function(){
		if ($(this).hasClass('tabs-selected')){
			return;
		}
		$('.tabs-nav a').removeClass('tabs-selected');
		$(this).addClass('tabs-selected');
		$('.tabs-slide').hide().filter('[id='+$(this).attr('rel')+']').fadeIn();
	});

  }); // document ready event
})(jQuery);

