
/*
 * @author: vinayks
 * checks for domainname validity with multiple domains supplied seperated by spaces or newline
 */


var messageList = new (function (){
    this.domainLong = "Domain name too long. It should be less than 63 characters.";
    this.domainError = "Invalid domain name! Please use only letters, numbers or dashes[-]. ";
    this.domainInternationalError = "We do not support international domain names.";
})();


function bulk_domain_text_verify(domainText) {
    domainText = domainText.replace(/,/g," ").replace(/^\s+|\s+$/g,"");
    if(domainText == "") {
        return domainNameError();
    }
    var line_sep_domain_texts = domainText.split("\n"); //split by new line
    var reg = /^[\w\d][\w\d\-\.]*[\w\d]$/;
    var domainTextWithoutTld = null;
    var space_sep_domain_texts = null;
    for(var i = 0;i < line_sep_domain_texts.length;i++){
        space_sep_domain_texts = line_sep_domain_texts[i].split(" "); //split by spaces
        for(var j = 0;j < space_sep_domain_texts.length;j++){
            space_sep_domain_texts[j] = space_sep_domain_texts[j].replace(/^\s+|\s+$/g,"");
            domainTextWithoutTld = space_sep_domain_texts[j].split(".");
            if(domainTextWithoutTld.length > 1) {
                domainTextWithoutTld.pop();
            }
            domainTextWithoutTld = domainTextWithoutTld.join(".");
            if ((space_sep_domain_texts[j] != "") && (!(reg.test(space_sep_domain_texts[j])) || (/_/.test(space_sep_domain_texts[j]))
                )) {
                return domainNameError();
            }
            if (domainTextWithoutTld.length > 63 )
            {
                return domainNameError(messageList.domainLong);
            }
        }
    }
    return true;
}

function CheckUsernameAvailability(usernameId, availability_check_url)
{
    var username = $(usernameId).value
    if ((username).strip()=="")
        return false;

    if (!(/^[A-Za-z0-9][A-Za-z0-9_]+[A-Za-z0-9]$/.test(username)))
    {
        return false;
    }

    new Ajax.Updater($("availability"), availability_check_url+"/?username="+username,
    {
        asynchronous:true,
        evalScripts:true,
        onComplete:function(request){
            $('spinner').hide();
            $("availability").show();
        },
        onLoading:function(request){
            $('spinner').show();
        }
    });
    return true;
}

/**
 * @author: Vinay (vinayks@limelabs.in)
 * Checks the element display and show and hides it depending on the current state
 */
function toggleElementDisplay(elemID, elemsToShow, elemsToHide) {
    var displayVar = $(elemID).style.display;
    if(displayVar == "") {
        $(elemID).hide();
        var tmp = elemsToHide;
        elemsToHide = elemsToShow;
        elemsToShow = tmp;
    }
    else {
        $(elemID).show();
    }
    var i = 0;
    for(i = 0; i < elemsToHide.length; i++){
        $(elemsToHide[i]).hide();
    }
    for(i = 0; i < elemsToShow.length; i++){
        $(elemsToShow[i]).show();
    }
}

function showHideMyAccountNav(theid,panel){
    if (document.getElementById(theid)) {
        var elem = document.getElementById(theid);
        if(elem.style.display == "") {
            elem.style.display = "none";
            createCookie(panel,'hide');
        } else {
            elem.style.display = "";
            createCookie(panel,'show');
        }
    }
}

function ShowDetailedComparison()
{
  scroll(0,600);
  $('features_row1').hide();
  $('features_row12').hide();
  $('thanks_row').hide();
  $('features_row22').show();
  $('features_row2').show();
  $('features_row').hide();
  Effect.toggle('detailed_page','blind',{
      afterFinish:function(){
          $('detailed_page').style.display ="inline-block";
      }
  });
  return false;
}

function HideDetailedComparison()
{

  scroll(0,600);
  $('features_row2').hide();
  Effect.toggle('detailed_page','blind',{
    afterFinish:function(){
      $('features_row').show();
      $('features_row1').show();
      $('features_row12').show();
      $('thanks_row').show();
      $('features_row22').hide();
    }
  });
  return false;
}

function tabPosition(){

    p1 = readCookie('p0');
    p2 = readCookie('p1');
    p3 = readCookie('p2');
    p4 = readCookie('p3');

    if(p1==null || p1=='show')
        $('acctMgmt').style.display = "";
    else
        $('acctMgmt').style.display = "none";

    if(p2==null || p2=='show')
        $('domainMgmt').style.display = "";
    else
        $('domainMgmt').style.display = "none";

    if(p3==null || p3=='show')
        $('emailMgmt').style.display = "";
    else
        $('emailMgmt').style.display = "none";

    if(p4==null || p4=='show')
        $('hostingMgmt').style.display = "";
    else
        $('hostingMgmt').style.display = "none";
}

function tabPosition1(){

    h1 = readCookie('h0');
    h2 = readCookie('h1');
    h3 = readCookie('h2');
    h4 = readCookie('h3');

    if(h1==null || h1=='show')
        $('general').style.display = "";
    else
        $('general').style.display = "none";

    if(h2==null || h2=='show')
        $('hostMgmt').style.display = "";
    else
        $('hostMgmt').style.display = "none";

    if(h4==null || h4=='show')
        $('emailMgmt').style.display = "";
    else
        $('emailMgmt').style.display = "none";

    if(h3==null || h3=='show')
        $('domainMgmt').style.display = "";
    else
        $('domainMgmt').style.display = "none";


}


function changeTab(contact_type){
    //uncheck the select all checkbox
    $("updateCBox").checked = false
    var tabs = ['billing','registrant','tech','admin'];
    for(i=0;i<4;i++) {
        if(contact_type == tabs[i]){
            $(contact_type + "_tab").className = "selected";
            $(contact_type + "_info").style.display ="";
        }
        else {
            $(tabs[i]+'_tab').className = "ns";
            $(tabs[i] + "_info").style.display ="none";
        }
    }
}

function verifyAgreement(){

    if( $('agreement') && !$('agreement').checked){
        refreshNotices("Please accept the Agreements and Terms & Conditions");
        scroll(0,0);
        return false;
    }
    $('purchase').hide();
    $('wait').show();
    return true;
}

function activateEdit(domain)
{
    document.getElementById(domain + "_edit").style.display='';
    document.getElementById(domain + "_val").style.display = 'none';
}

function cancelEdit(domain)
{
    document.getElementById(domain + "_edit").style.display='none';
    document.getElementById(domain + "_val").style.display = '';
}

function updateAll()
{
    var updateCBox = $('updateCBox');
    var tabs = ['billing','registrant','tech','admin'];
    var tabAll = $('all_tab');

    if(updateCBox.checked)
    {
        tabAll.style.display = "";
        $("all_info").style.display = "";
        for(i=0;i<4;i++){
            $(tabs[i]+'_tab').style.display = "none";
            $(tabs[i]+'_info').style.display = "none";
        }
    }
    else
    {
        tabAll.style.display = "none";
        $("all_info").style.display = "none";

        for(i=0;i<4;i++){
            var tab = $(tabs[i]+'_tab');
            tab.style.display = "";
            var class_style,display_style;
            if(tabs[i] == "billing"){
                class_style = "selected";
                display_style = "" ;
            }
            else{
                class_style = "ns";
                display_style = "none";
            }
            tab.className = class_style;
            $(tabs[i]+'_info').style.display = display_style;
        }
    }
}

function dirtyForm(form_id){
    var chk_form = document.getElementById(form_id)
    var el, i = 0;
    while (el = chk_form.elements[i++]) {
        if(el.type == 'text' ||el.type == 'textarea')
            if (el.value != el.defaultValue)
                return true;
    }
    refreshNotices("No fields were changed");
    return false;
}

function checkFields(form_id){
    if(!chkFormRequiredFields(form_id) || !chkVerification() || !chkCleanInput(form_id)) return false;
    return true;
}


// add class "number" to element.
// error displayed: "element.id should be a number." (Set id correctly.)
function checkNumberFields(form_id){
    numreg = /^\d*$/ ;
    var form_elems = document.getElementById(form_id).select(".number");
    for(var i=0;i < form_elems.length;i++) {
        if(!numreg.test(form_elems[i].value)){
            refreshNotices(form_elems[i].id + " should be a number");
            return false;
        }
    }

    return true;
}

function checkAsciiFields(form_id){
    asciireg = /^[\x20-\x7E]*$/;
    var form_elems = document.getElementById(form_id).select(".ascii");
    for(var i=0;i < form_elems.length;i++) {
        if(!asciireg.test(form_elems[i].value)){
            refreshNotices("Non ASCII characters are not allowed");
            return false;
        }
    }
    
    return true;
}

function billing_checks(){
    zip = $('Zip')
    phone= $('Phone')
    phone_cc = $('PhoneCC')
    if(! /^[a-zA-Z0-9][ a-zA-Z0-9-]{0,9}$/.test(zip.value)){
        refreshNotices("Invalid zip");
        return false;
    }
    if(!(phone_cc.value.length > 0 && phone_cc.value.length <5)){
        refreshNotices("Phone Country Code should be 1 to 4 characters in length.");
        return false;
    }
    if(!(phone.value.length > 3 && phone.value.length <13)){
        refreshNotices("Phone number should be 4 to 12 characters in length.");
        return false;
    }
    return true;
}

function callFloats(pWidth, obj)
{
    var winL = (screen.width - pWidth) / 2;
    var winH = "200";

    winL = winL + 103;
    if(obj.toString().substr(0,14)=='addAutoRespond'||obj.toString().substr(0,17) =='modifyAutoRespond') {
        winL = (screen.width - pWidth) / 2;
        winH = "90";
    }

    var floatingDiv = document.getElementById("floatingDiv");
    var floatContainer = document.getElementById("floatContainer");
    var floatContent = document.getElementById("floatContent");


    floatingDiv.style.display="";
    floatContainer.style.display="";
    floatContent.style.display="";
    floatingDiv.style.height = document.body.scrollHeight;

    //alert(2);
    floatContainer.style.width = pWidth;

    floatContainer.style.left=winL;
    floatContainer.style.top=winH;
    floats = $$('div[name=float]');
    for(var i=0;i<floats.length;i++){
        if(floats[i].id == obj){
            floats[i].show();
        }
        else
            floats[i].hide();
    }
    $('processQuota').hide();
}

function callFloatsCart(pWidth, obj, avoidObjects)
{
    //  alert('now inside call floats cart');
    var winL = (screen.width - pWidth) / 2;
    var winH = "200";
    var floatingDiv = document.getElementById("floatingDiv");
    var floatContainer = document.getElementById("floatContainer");
    var floatContent = document.getElementById("floatContent");
    floatingDiv.style.height = document.body.scrollHeight+'px';
    floatContainer.style.width = pWidth;
    floatContainer.style.left=winL;
    floatContainer.style.top=winH;
    floatContainer.style.display="";
    floatContent.style.display="";
    floatingDiv.style.display="";
    floats = $$('div[name=float]');
    for(var i=0;i<floats.length;i++){
        if(floats[i].id == obj){
            floats[i].show();
        }
        else
            floats[i].hide();
    }

    //avoids = ['tld_select']
    //if(avoidObjects){
    //   avoids = avoids.concat(avoidObjects)
    //}
    // Detect IE 6
    if (window.external && typeof window.XMLHttpRequest == "undefined")
    {
        troublesomeDivVisibility('hidden', avoidObjects);
    }
// scroll(0,0);
// alert('EXITING call floats cart');
}

function troublesomeDivVisibility(status, avoid){
    tag=document.getElementsByTagName('select');
    for(i=tag.length-1;i>=0;i--){
        tag[i].style.visibility=status;
    }
    tag=document.getElementsByTagName('iframe');
    for(i=tag.length-1;i>=0;i--){
        tag[i].style.visibility=status;
    }
    tag=document.getElementsByTagName('object');
    for(i=tag.length-1;i>=0;i--){
        tag[i].style.visibility=status;
    }

    if(avoid){
        for(var i=0, len = avoid.length; i < len; ++i){
            element = $(avoid[i]);
            if(element){
                element.style.visibility='visible';
            }
        }
    }
}

function closeFloatsCart(obj)
{
    document.getElementById("floatingDiv").style.display="none";
    document.getElementById("floatContainer").style.display="none";
    document.getElementById("floatContent").style.display = "none";
    $(obj).style.display = "none";
    //if (window.external && typeof window.XMLHttpRequest == "undefined")
    troublesomeDivVisibility('visible');
}

function closeFloats(obj)
{
    document.getElementById("floatingDiv").style.display="none";
    document.getElementById("floatContainer").style.display="none";
    document.getElementById("floatContent").style.display = "none";
    $(obj).style.display = "none";
}

function show_confirmation(id,name){
    $('form_id').value = id;
    $('warning').innerHTML = 'Are you sure you want to delete email account ' + name + ' ?';
    callFloatsCart('700','emailDelete');
}

function show_confirmation_forward_create(text,form_name,delete_item){
    $('form_id').value = form_name;
    $('warning').innerHTML = text;
    scroll(0,0);
    callFloatsCart('700',delete_item,[]);
    return false;
}


function show_confirmation_hosting(name,form_name,delete_item){
    $('form_id').value = form_name;
    $('warning').innerHTML = 'Are you sure you want to delete '+ name +'?';
    scroll(0,0);
    callFloatsCart('700',delete_item,[]);
    return false;
}

function show_confirmation_hosting_files(form_name,delete_item,class_name){
    boxes = document.getElementsByClassName(class_name)
    $('form_id').value = form_name;
    var empty = true;
    var numCheck = 0
    for(var i=0;i<boxes.length;i++){
        if(boxes[i].checked){
            empty = false;
            numCheck += 1;
            $(form_name+'_path').show();
            $('copy_path_text').show();
            $('move_path_text').show();
            $('extract_path_text').show();
            $('compress_path_text').show();
            var newField = document.createElement("input");
            newField.type = "hidden";
            newField.name = boxes[i].name;
            newField.value = boxes[i].value;
            newField.className = 'added_element';
            if (form_name == 'copy_file'){
                $('copy_files').appendChild(newField);
            }
            if (form_name == 'move_file'){
                $('move_files').appendChild(newField);
            }
            if(form_name == 'compress_file'){
                $('compress_files').appendChild(newField);
            }
            if (form_name == 'extract_file' || form_name == 'change_permission_file' || form_name == 'edit_file'){
                if(numCheck > 1){
                    $('extract_warning').innerHTML = 'Multiple files selected, please select only one archive to extract.';
                    $('change_permission_warning').innerHTML = 'Multiple files selected, please select only one file for changing its permissions.';
                    $('extract_file_path').hide();
                    $('extract_path_text').hide();
                    $('change_permission_file_path').hide();
                    callFloatsCart('700',delete_item,[]);
                    $('form_id').value = "no_files";
                    scroll(0,0);
                    return false;
                }
                if(form_name == 'extract_file'){
                    $('extract_files').appendChild(newField)
                }
                if(form_name == 'edit_file'){
                    $('edit_files').appendChild(newField)
                }
                if(form_name == 'change_permission_file'){
                    $('change_permission_files').appendChild(newField);
                    check_existing_perms(newField.value);
                }
            }
        }
    }
    if(empty){
        $(form_name+'_path').hide();
        $('copy_path_text').hide();
        $('move_path_text').hide();
        $('extract_path_text').hide();
        $('compress_path_text').hide();
        $('warning').innerHTML = 'No files selected!';
        $('copy_warning').innerHTML = 'No files selected!';
        $('move_warning').innerHTML = 'No files selected!';
        $('extract_warning').innerHTML = 'No files selected!';
        $('compress_warning').innerHTML = 'No files selected!';
        $('change_permission_warning').innerHTML = 'No files selected!';
        $('form_id').value = "no_files";
        callFloatsCart('700',delete_item,[]);
        return false;
    }else{
        if(form_name == 'copy_file'){
            $('copy_warning').innerHTML = 'Enter the path to which the selected files are to be copied. This path is relative to your plan root: ';
        }else{
            if(form_name == 'move_file'){
                $('move_warning').innerHTML = 'Enter the path to which the selected files are to be moved. This path is relative to your plan root: ';
            }
            if(form_name == 'extract_file'){
                $('extract_warning').innerHTML = 'Enter the path to which the selected archive is to be extracted. This path is relative to your plan root. Leaving the path blank would extract it to the current directory ';
            }
            if(form_name == 'compress_file'){
                $('compress_warning').innerHTML = 'Enter the name of archive to which the selected files are to be compressed into.(Only .zip archives are allowed.)';
            }
            if(form_name == 'change_permission_file'){
                $('change_permission_warning').innerHTML = 'Please select the permissions you wish to specify for the selected file.';
            }
            else{
                $('warning').innerHTML = 'Are you sure you want to delete the selected files? ';
            }
        }
        callFloatsCart('700',delete_item,[]);
        try{
            $(form_name+'_path').focus();
        }catch(e){
        }
        scroll(0,0);
        return false;
    }
}

function cancel_single_file_only(form_name,class_name){
    elements = document.getElementsByClassName(class_name)
    for(var i=0;i<elements.length;i++){
        newField = elements[i];
        $(form_name).removeChild(newField);
    }
    closeFloatsCart('files');
}


function check_existing_perms(perm){
    var user_perm = perm.charAt(0);
    var group_perm = perm.charAt(1);
    var world_perm = perm.charAt(2);

    var user_read_checkbox = $('user_read');
    var user_write_checkbox = $('user_write');
    var user_execute_checkbox = $('user_execute');

    var group_read_checkbox = $('group_read');
    var group_write_checkbox = $('group_write');
    var group_execute_checkbox = $('group_execute');

    var world_read_checkbox = $('world_read');
    var world_write_checkbox = $('world_write');
    var world_execute_checkbox = $('world_execute');

    user_perm = parseInt(user_perm);
    group_perm = parseInt(group_perm);
    world_perm = parseInt(world_perm);
    switch(user_perm){
        case 7:
            user_read_checkbox.checked = true;
            user_write_checkbox.checked = true;
            user_execute_checkbox.checked = true;
            break;
        case 6:
            user_read_checkbox.checked = true;
            user_write_checkbox.checked = true;
            user_execute_checkbox.checked = false;
            break;
        case 5:
            user_read_checkbox.checked = true;
            user_write_checkbox.checked = false;
            user_execute_checkbox.checked = true;
            break;
        case 4:
            user_read_checkbox.checked = true;
            user_write_checkbox.checked = false;
            user_execute_checkbox.checked = false;
            break;
        case 3:
            user_read_checkbox.checked = false;
            user_write_checkbox.checked = true;
            user_execute_checkbox.checked = true;
            break;
        case 2:
            user_read_checkbox.checked = false;
            user_write_checkbox.checked = true;
            user_execute_checkbox.checked = false;
            break;
        case 1:
            user_read_checkbox.checked = false;
            user_write_checkbox.checked = false;
            user_execute_checkbox.checked = true;
            break;
        case 0:
            user_read_checkbox.checked = false;
            user_write_checkbox.checked = false;
            user_execute_checkbox.checked = false;
        default:
            break;
    }
    switch(group_perm){
        case 7:
            group_read_checkbox.checked = true;
            group_write_checkbox.checked = true;
            group_execute_checkbox.checked = true;
            break;
        case 6:
            group_read_checkbox.checked = true;
            group_write_checkbox.checked = true;
            group_execute_checkbox.checked = false;
            break;
        case 5:
            group_read_checkbox.checked = true;
            group_write_checkbox.checked = false;
            group_execute_checkbox.checked = true;
            break;
        case 4:
            group_read_checkbox.checked = true;
            group_write_checkbox.checked = false;
            group_execute_checkbox.checked = false;
            break;
        case 3:
            group_read_checkbox.checked = false;
            group_write_checkbox.checked = true;
            group_execute_checkbox.checked = true;
            break;
        case 2:
            group_read_checkbox.checked = false;
            group_write_checkbox.checked = true;
            group_execute_checkbox.checked = false;
            break;
        case 1:
            group_read_checkbox.checked = false;
            group_write_checkbox.checked = false;
            group_execute_checkbox.checked = true;
            break;
        case 0:
            group_read_checkbox.checked = false;
            group_write_checkbox.checked = false;
            group_execute_checkbox.checked = false;
            break;
        default:
            break;
    }

    switch(world_perm){
        case 7:
            world_read_checkbox.checked = true;
            world_write_checkbox.checked = true;
            world_execute_checkbox.checked = true;
            break;
        case 6:
            world_read_checkbox.checked = true;
            world_write_checkbox.checked = true;
            world_execute_checkbox.checked = false;
            break;
        case 5:
            world_read_checkbox.checked = true;
            world_write_checkbox.checked = false;
            world_execute_checkbox.checked = true;
            break;
        case 4:
            world_read_checkbox.checked = true;
            world_write_checkbox.checked = false;
            world_execute_checkbox.checked = false;
            break;
        case 3:
            world_read_checkbox.checked = false;
            world_write_checkbox.checked = true;
            world_execute_checkbox.checked = true;
            break;
        case 2:
            world_read_checkbox.checked = false;
            world_write_checkbox.checked = true;
            world_execute_checkbox.checked = false;
            break;
        case 1:
            world_read_checkbox.checked = false;
            world_write_checkbox.checked = false;
            world_execute_checkbox.checked = true;
            break;
        case 0:
            world_read_checkbox.checked = false;
            world_write_checkbox.checked = false;
            world_execute_checkbox.checked = false;
            break;
        default:
            break;
    }
}

function confirmation_delete_files_hosting(){
    var form = $('form_id').value;
    if(form == "no_files"){
        cancel_single_file_only('change_permission_files','added_element');
        cancel_single_file_only('extract_files','added_element');
        closeFloatsCart('files');
    }
    else{
        var deleteInput = document.createElement('input');
        deleteInput.name = "delete";
        $(form).appendChild(deleteInput);
        $(form).submit();
    }
}

function confirmation_file_action_hosting(submit_form){
    var form = $('form_id').value;
    if(form == "no_files"){
        closeFloatsCart('files');
        cancel_single_file_only(submit_form,'added_element');
    }else{
        $(submit_form).submit();
    }
}

function confirmation_delete_hosting(){
    var form = $('form_id').value;
    $(form).submit();
}

function confirm_delete(){

    var form_id = $('form_id').value;
    var form_name = 'delete_account_' + form_id
    $(form_name).submit();
}
/**
  * Checks the required fields of a form
  */
function chkFormRequiredFields(form_id) {
    var form_elems = $(form_id).select(".required");
    for(var i=0;i < form_elems.length;i++)
        if(!form_elems[i].disabled && /^\s*$/.test(form_elems[i].value)){
            refreshNotices("Fields marked as * can not be empty");
            return false;
        }

    return true;
}

/**
  * Author: Amit Kumar (amitkr@limespot.co.in)
  *
  * Checks the required fields of a form
  */

//
//function ResetValidations(form_id){
//  var z=0;
//  for(var i=0; i < valid_array.length;i++) {
//
//	if (valid_array[i])
//	{
//	 valid_array[i].destroy();
//         delete valid_array[i];
//	 }
//       }
//       console.log(valid_array);
//
//  //alert(1);
//  SetChkFormFields(form_id);
//}

function SetChkFormFields(form_id) {
    var form_elems = $(form_id)
    var valid_array = new Array();
    for(var i=0; i < form_elems.length; i++) {
        Element.extend(form_elems[i]);
        if (!(((form_elems[i].type == 'hidden')||(form_elems[i].type == 'submit')) ||form_elems[i].hasClassName('skipValid') ))
        {
            if (form_elems[i].hasClassName('PhoneCC') || form_elems[i].hasClassName(''))
            {
                valid_array[i] = new LiveValidation(form_elems[i],{
                    validMessage: " ",
                    onlyOnSubmit: true,
                    insertAfterWhatNode: document.getElementById("phone_cc_error"),
                    onInvalid: function(){
                        this.insertMessage( this.createMessageSpan() );
                        this.addFieldClass();
                        scroll(0,0);
                    }
                });		// ,onlyOnSubmit: true,                refreshNotices("PhoneCC must be a number and between 1-3 digits.");
            }
            else
            {
                if (form_elems[i].hasClassName('AltPhoneCC'))
                {
                    valid_array[i] = new LiveValidation(form_elems[i],{
                        validMessage: " ",
                        onlyOnSubmit: true,
                        insertAfterWhatNode: document.getElementById("alt_phone_cc_error"),
                        onInvalid: function(){
                            this.insertMessage( this.createMessageSpan() );
                            this.addFieldClass();
                            scroll(0,0);
                        }
                    });		// ,onlyOnSubmit: true,                refreshNotices("PhoneCC must be a number and between 1-3 digits.");
                }
                else
                {
                    if (form_elems[i].hasClassName('AltFaxCC'))
                    {
                        valid_array[i] = new LiveValidation(form_elems[i],{
                            validMessage: " ",
                            onlyOnSubmit: true,
                            insertAfterWhatNode: document.getElementById("alt_fax_cc_error"),
                            onInvalid: function(){
                                this.insertMessage( this.createMessageSpan() );
                                this.addFieldClass();
                                scroll(0,0);
                            }
                        });		// ,onlyOnSubmit: true,                refreshNotices("PhoneCC must be a number and between 1-3 digits.");
                    }
                    else
                    {
                        valid_array[i] = new LiveValidation(form_elems[i],{
                            validMessage: " ",
                            onlyOnSubmit: true,
                            onInvalid: function(){
                                this.insertMessage( this.createMessageSpan() );
                                this.addFieldClass();
                                scroll(0,0);
                            }
                        });
                    }
                }
            }
            //Register page error message positioning

            if (form_elems[i].hasClassName('specified_error'))
            {
                valid_array[i] = new LiveValidation(form_elems[i],{
                    validMessage: " ",
                    onlyOnSubmit: true,
                    insertAfterWhatNode: document.getElementById(form_elems[i].id+"_error"),
                    onInvalid: function(){
                        this.insertMessage( this.createMessageSpan() );
                        this.addFieldClass();
                        scroll(0,0);
                    }
                });
            }
      
            if (form_elems[i].hasClassName("number"))
                valid_array[i].add(Validate.Numericality,{
                    minimum: 0,
                    onlyInteger: true
                });
            if (form_elems[i].hasClassName("required"))
                valid_array[i].add(Validate.Presence);
            if (form_elems[i].hasClassName('PhoneCC')||form_elems[i].hasClassName('AltPhoneCC')||form_elems[i].hasClassName('AltFaxCC'))
                valid_array[i].add(Validate.Length,{
                    maximum: 4,
                    tooLongMessage: "Too Long."
                });
            if (form_elems[i].hasClassName('Phone'))
                valid_array[i].add(Validate.Length,{
                    minimum: 4,
                    maximum: 12,
                    tooShortMessage: "Atleast 4 characters.",
                    tooLongMessage: "Max 12 characters."
                });
            if (form_elems[i].hasClassName('Zip'))
                valid_array[i].add(Validate.Format,{
                    pattern: /^[a-zA-Z0-9][ a-zA-Z0-9-]{0,9}$/,
                    failureMessage: "Invalid zip."
                });
            if (form_elems[i].hasClassName('email'))
                valid_array[i].add(Validate.Email,{
                    failureMessage: "Invalid Email."
                });
            if (form_elems[i].hasClassName('retype_password'))
            {
                valid_array[i].add(Validate.Confirmation,{
                    match: "password_create",
                    failureMessage: "Passwords don't match."
                });
            }
            if (form_elems[i].hasClassName('password'))
                valid_array[i].add(Validate.Length,{
                    minimum: 6,
                    tooShortMessage: "Atleast 6 characters."
                });
            if (form_elems[i].hasClassName('retype_email'))
                valid_array[i].add(Validate.Confirmation,{
                    match: "email",
                    failureMessage: "Emails don't match."
                });
            if (form_elems[i].hasClassName('username'))
                valid_array[i].add(Validate.Format,{
                    pattern: /^[A-Za-z0-9][A-Za-z0-9_]+[A-Za-z0-9]$/,
                    failureMessage: "Only characters [A-Z, a-z, 0-9] and _ allowed."
                });
            if (form_elems[i].hasClassName('notdirty'))
                valid_array[i].add(Validate.Format,{
                    pattern: /\%|\$|\<|\>|#/,
                    negate: true,
                    failureMessage: "$ % < > # not allowed"
                });
            if (form_elems[i].hasClassName('ascii'))
                valid_array[i].add(Validate.Format,{
                    pattern: /^[\x20-\x7E]*$/,
                    failureMessage: "Non ASCII characters are not allowed"
                });
            if (form_elems[i].hasClassName('subdomain'))
                valid_array[i].add(Validate.Custom,{
                    against: function(value,args){
                        var subdomain_reg = /^([a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?$/;
                        var test_value = value.strip();
                        // return true if its not required field and the value is blank
                        if ((test_value == "") && !(form_elems[i].hasClassName("required"))){
                            return true;
                        }
                        if (!(subdomain_reg.test(test_value))){
                            refreshNotices(value + " is not a valid subdomain");
                            return false;
                        }
                        return true;
                    },
                    args: {},
                    failureMessage: " "
                });
            if (form_elems[i].hasClassName('IP'))
                valid_array[i].add(Validate.Custom,{
                    against: function(value,args){
                        return validateIPAddr(value);
                    },
                    args: {},
                    failureMessage: " "
                });
        
            if (form_elems[i].hasClassName('IPv6'))
                valid_array[i].add(Validate.Custom,{
                    against: function(value,args){
                        return validateIPv6Addr(value);
                    },
                    args: {},
                    failureMessage: "Not a valid IPv6 address"
                });
        //if (form_elems[i].hasClassName('PhoneCC'))
        //valid_array[i].destroy();
        }
    }
}


// checks all inputs for invalid characters.
function chkCleanInput(form_id){
    var form = document.getElementById(form_id)
    var el, i = 0;
    while (el = form.elements[i++]) {
        if(el.type == 'text' || el.type == 'password' ||
            el.type == 'select' || el.type=='radio' || el.type=='textarea')
            if (/\%|\$|\<|\>/.test(el.value)){
                hideNotices();
                document.getElementById("boxError").style.display="";
                changeOpac(100,"boxError");
                //document.getElementById("boxError").style.opacity=100;
                document.getElementById("errorContent").innerHTML="Please do not enter % < > $ characters.";
                el.focus();
                return false;
            }
    }
    return true;
}



function chkVerification(){
    if(document.getElementsByName("new_password")[0])
        if(document.getElementsByName("new_password")[0].value != document.getElementsByName("new_password2")[0].value){
            document.getElementsByName("new_password")[0].value ="";
            document.getElementsByName("new_password2")[0].value ="";
            refreshNotices("Password does not match confirmation.");
            return false;
        }
    return true;
}

function hideNotices(){
    document.getElementById("boxSuccess").style.display ="none";
    document.getElementById("boxError").style.display ="none";
}


function submitAllContacts(){
    var all_form = document.getElementById("all_form");
    var contact_forms = [document.getElementById("billing_form"),document.getElementById("registrant_form"),
    document.getElementById("tech_form"),document.getElementById("admin_form")];
    var el, i = 0;
    while (el = all_form.elements[i]) {

        if(el.type == 'text')
            for(j=0;j<4;j++){
                if (el.value != contact_forms[j].elements[i].value)
                {
                    return true;
                }
            }
        i++;
    }
    refreshNotices("No fields were changed");

    return false;
}

function changeType(){
    if($("local_account").checked) {
        $('local_account_name').disabled = false;
        $('local_account_domain').disabled = false;
        $('outside_account_name').disabled = true;
        $('outside_account_domain').disabled = true;
        $('local_account_name').focus();
        $('outside_info').hide();
    }
    if ($("outside_account").checked){
        $('local_account_name').disabled = true;
        $('local_account_domain').disabled = true;
        $('outside_account_name').disabled = false;
        $('outside_account_domain').disabled = false;
        $('outside_account_name').focus();
        $('outside_info').show();
    }
}

function disableByClassName(classname, disable){
  var selector = 'input[class~="' + classname + '"]';
  $$(selector).each(function(elem) {
    elem.disabled = disable;
  });
  var selector = 'textarea.' + classname
  $$(selector).each(function(elem) {
    elem.disabled = disable;
  });
  var selector = 'select.' + classname
  $$(selector).each(function(elem) {
    elem.disabled = disable;
  });
}

function toggleDisplayByClassName(classname, hide){
    var selector = '.' + classname;
    $$(selector).each(function(elem) {
        if(hide)
            elem.hide();
        else
            elem.show();
    });
}

function toggleInputDivs(showClass, hideClass){
  toggleDisplayByClassName(hideClass, true);
  toggleDisplayByClassName(showClass, false);
  disableByClassName(showClass, false);
  disableByClassName(hideClass, true);
}

function toggleExternalDisplay(hide){
    var keyInputElement = $('outside_domain_name');
    if(keyInputElement) {
        toggleDisplayByClassName('external_domain_inputs', hide);
        keyInputElement.disabled = hide;
    }
}

function toggleTrialDisplay(hide){
    var keyInputElement = $('trial_subdomain_name');
    if(keyInputElement) {
        toggleDisplayByClassName('subdomain_inputs', hide)
        keyInputElement.disabled = hide;
    }
}

function toggleLocalDomainDisplay(hide){
    var keyInputElement = $('local_account_domain');
    if(keyInputElement){
        toggleDisplayByClassName('local_domain_inputs', hide);
        keyInputElement.disabled = hide;
        if(!hide)
            keyInputElement.focus();
    }
}

function toggleLimewebsDisplay(hide){
    var keyInputElement = $('local_limewebs_account');
    if(keyInputElement) {
        toggleDisplayByClassName('local_limewebs_inputs', hide)
    }
}


function toggleLocalSubDomainDisplay(hide){
    var keyInputElement = $('local_subdomain_name');
    if(keyInputElement){
        toggleDisplayByClassName('local_subdomain_inputs', hide);
        keyInputElement.disabled = hide;
    }
}

function changeWebsiteType(){
    if($('domainNameTxt')){
        $('domainNameTxt').disabled = true;
    }
    if($('local_account') && $('local_account').checked){
        // User wants to host a domain purchased from his account.
        toggleExternalDisplay(true);
        toggleTrialDisplay(true);
        toggleLocalSubDomainDisplay(true);
        toggleLocalDomainDisplay(false);
        toggleLimewebsDisplay(true);
        if($('domain_selection_box'))
            $('domain_selection_box').show();
    }

    if($('local_limewebs_account') && $('local_limewebs_account').checked){
        // User wants to host a domain purchased from his account.
        toggleExternalDisplay(true);
        toggleTrialDisplay(true);
        toggleLocalSubDomainDisplay(true);
        toggleLocalDomainDisplay(true);
        toggleLimewebsDisplay(false);
        if($('domain_selection_box'))
            $('domain_selection_box').show();
    }

    if($('local_subdomain_account') && $('local_subdomain_account').checked){
        toggleExternalDisplay(true);
        toggleTrialDisplay(true);
        toggleLocalDomainDisplay(true);
        toggleLimewebsDisplay(true);
        toggleLocalSubDomainDisplay(false);
    }

    if($('outside_account') && $("outside_account").checked){
        // User has chosen to use his own domain name.
        toggleLocalDomainDisplay(true);
        toggleTrialDisplay(true);
        toggleLocalSubDomainDisplay(true);
        toggleLimewebsDisplay(true);
        toggleExternalDisplay(false);
    }

    if($('trial_account') && $("trial_account").checked){
        // User has chosen to create a website on a subdomain of limedemo.com
        toggleLocalDomainDisplay(true);
        toggleExternalDisplay(true);
        toggleLocalSubDomainDisplay(true);
        toggleLimewebsDisplay(true);
        toggleTrialDisplay(false);
        if($('domain_selection_box'))
            $('domain_selection_box').hide();
    }
}

function toggleDocumentRootOptions(classname, checkboxElement){
    var checkStatus = !checkboxElement.checked;
    disableByClassName(classname, checkStatus);
    toggleDisplayByClassName(classname, checkStatus);
}

function changeLocationType(){
    if($('location_dir').checked){
        $('textfield4').disabled = false;
        $('subdomain').disabled = true;
        $('textfield4').focus();
    }
    if($('location_subdomain').checked){
        $('textfield4').disabled = true;
        $('subdomain').disabled = false;
        $('subdomain').focus();
    }
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function prepareInputsForDescription() {
    var inputs = document.getElementsByTagName("input");
    for (var i=0; i<inputs.length; i++){
        var input_name = inputs[i].name;
        if(inputs[i].parentNode.className =="value")
            if(inputs[i].parentNode.parentNode.getElementsByTagName("span")[0])
                if(inputs[i].parentNode.parentNode.getElementsByTagName("span")[0].id == (input_name + '_desc') ){
                    inputs[i].onfocus = function () {
                        var object = this.parentNode.parentNode.getElementsByTagName("span")[0].style;
                        object.opacity = (1);
                        object.MozOpacity = (1);
                        object.KhtmlOpacity = (1);
                        object.filter = "alpha(opacity=" + 100 + ")";
                    }

                    inputs[i].onblur = function () {
                        var object = this.parentNode.parentNode.getElementsByTagName("span")[0].style;
                        object.opacity = (0);
                        object.MozOpacity = (0);
                        object.KhtmlOpacity = (0);
                        object.filter = "alpha(opacity=" + 0 + ")";
                    //          this.parentNode.parentNode.getElementsByTagName("span")[0].style.opacity = 0;
                    }
                }
    }

}

function showMoreBox(obj)
{
    var addEmailBox = $("addEmailBox");
    if(obj == "more_box")
        addEmailBox.style.display = "";
    else
        addEmailBox.style.display = "none";
}

function showMoreQuota(obj)
{
    var addQouta = $("addQouta");
    if(obj == "more_quota")
        addQouta.style.display = "";
    else
        addQouta.style.display = "none";
}


/**
   * Author : Vinay (vinayks@limespot.co.in)
   * Validates a URL
   * valid_urls : vinayks.com, www.vinayks.com, http://www.vinayks.com
   * invalid_urls : vinayks, vinayks.
   *
   */
function validate_url(url)
{
    var re = new RegExp("^(http[s]?://)?([a-zA-Z0-9-]+\\.)+[a-zA-Z0-9-]+(/(.*))?$");
    var match = re.exec(url);
    if(match == null)
    {
        refreshNotices("Invalid URL<br><br>");
        return false;
    }
    return true;
}

/**
   * Author : Vinay (vinayks@limespot.co.in)
   * Validates a domain name
   * valid_urls : vinayks.com, www.vinayks.com, http://www.vinayks.com
   * invalid_urls : vinayks, vinayks.
   *
   */
function validate_domain(domainname)
{
    var re = new RegExp("^([a-zA-Z0-9-]+\\.)+[a-zA-Z0-9-]+$");
    var match = re.exec(domainname);
    if(match == null)
    {
        refreshNotices(domainname + " is not a valid domain name!!");
        return false;
    }
    return true;
}

function validateSubdomain(subdomain, docroot_val) {
    var valid_docroot = (docroot_val == "") || validate_hosting_path(docroot_val);
    var valid_subdomain =  false;
    if(subdomain == "") {
        refreshNotices("Subdomain cannot be empty");
    }
    else {
        var reg = /^([\w\d]([\w\d\-]*[\w\d])?\.)*[\w\d]([\w\d\-]*[\w\d])?$/
        valid_subdomain = !(!reg.test(subdomain) || /_/.test(subdomain))
        if(!valid_subdomain)
            refreshNotices(subdomain + " is an invalid subdomain");
    }
    return valid_subdomain && valid_docroot;
}

function validateNSForm(form_id, className, checkDirtyForm) {
    var valid_ns = true;
    var no_duplicate_ns = true;
    var invalidNames =""
    var boxes = $$("." + className);
    var nameservers = [];
    for(var i=0;i<boxes.length;i++){
        if (boxes[i].value!= ''){
            if(!validate_domain(boxes[i].value))
            {
                // if (boxes[i].value != ''){
                valid_ns = false;
                invalidNames += boxes[i].value + " ,";
            //      }
            }
            else{
                if (nameservers.include(boxes[i].value)){
                    no_duplicate_ns = false ;
                }
                nameservers.push(boxes[i].value);
            }
        }
    }

    if(!valid_ns)
        refreshNotices("Invalid Nameservers : " + invalidNames.substr(0, invalidNames.length -1));
    else{
        if (!no_duplicate_ns)
            refreshNotices("Duplicate nameserver enteries found. Please make sure you provide different nameserver entries.");
    }
    return (checkDirtyForm ? dirtyForm(form_id) : true) && chkFormRequiredFields(form_id) && valid_ns && no_duplicate_ns;
}



/**
   * Author : Vinay(vinayks@limespot.co.in)
   * validates a IP Address(currently just IPV4)
   * IPv6 done below. TODO make it verbose
   */
function validateIPAddr (IPvalue) {
    errorString = "";
    theName = "IPaddress";

    var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
    var ipArray = IPvalue.match(ipPattern);

    if (IPvalue == "0.0.0.0")
        errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
    else if (IPvalue == "255.255.255.255")
        errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
    if (ipArray == null)
        errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';
    else {
        for (i = 0; i < 4; i++) {
            thisSegment = ipArray[i];
            if (thisSegment > 255) {
                errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';
                i = 4;
            }
            if ((i == 0) && (thisSegment > 255)) {
                errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
                i = 4;
            }
        }
    }
    extensionLength = 3;
    if (errorString != "")
    {
        refreshNotices(errorString);
        return false;
    }
    return true;
}

/**
   * Author : Vinay(vinayks@limespot.co.in)
   * selects all the checkboxes identified by the given checkbox id in the given form
   */
function selectAll(form_id, checkbox_id)
{
    form_elems = document.getElementById(form_id).elements;
    for(i = 0;i < form_elems.length;i++)
    {
        if(form_elems[i].type == 'checkbox' && form_elems[i].id == checkbox_id)
        {
            form_elems[i].checked = true;
        }
    }
}

/**
   * Author : Vinay(vinayks@limespot.co.in)
   * deselects all the checkboxes identified by the given checkbox id in the given form
   */
function deselectAll(form_id, checkbox_id)
{
    form_elems = document.getElementById(form_id).elements;
    for(i = 0;i < form_elems.length;i++)
    {
        if(form_elems[i].type == 'checkbox' && form_elems[i].id == checkbox_id)
        {
            form_elems[i].checked = false;
        }
    }
}

/**
   * Author : Amit(amitkr@limespot.co.in)
   * Toggle a set of checkboxes based on some other checkbox
   */

function toggleAll(CheckBoxId,to_check_array)
{
    if ($(CheckBoxId).checked == true)
    {
        var i;
        for (i=0; i < to_check_array.length; i++)
        {
            if ($(to_check_array[i]))
            {
                if ($(to_check_array[i]).type == 'checkbox')
                {
                    $(to_check_array[i]).checked = true;
                }
            }
        }
    }
    else
    {
        var i;
        for (i=0; i < to_check_array.length; i++)
        {
            if ($(to_check_array[i]))
            {
                if ($(to_check_array[i]).type == 'checkbox')
                {
                    $(to_check_array[i]).checked = false;
                }
            }
        }
    }
}

/**
   * Author : Vinay(vinayks@limespot.co.in)
   * deselects all the checkboxes identified by the given checkbox id in the given form
   */
function refreshNotices(message)
{
    hideNotices();
    $("boxError").style.display = "";
    changeOpac(100,"boxError");
    //$("boxError").style.opacity = 100;
    $("errorContent").innerHTML = message;
    scroll(0,0);
}




function validateModifyAntiSpamInput(form_id)
{
    form = $(form_id);
    form_elem_array = form.elements ;
    for(i=0; i < form_elem_array.length; i++) {
        f = form_elem_array[i] ;
        if( f.id == "modifyAnti_folder") {
            folder = f.value;
        }
        else if( f.id == "modifyAnti_threshold") {
            threshold = f.value.to_i;
        }
    }

    invalid = false;
    error_message = "";
    if(folder=="") {
        invalid = true;
        error_message="Folder name is empty. Please enter a folder name"
    }
    else if(threshold <= 0)
    {
        invalid = true;
        error_message="Threshold has to be greater than 0. Please Enter a valid threshold"
    }

    if (invalid)
    {
        refreshNotices(error_message);
        return false;
    }
    return true;
}



























/**
   * Author : Ritesh Sinha(sinha.riteshk@limespot.co.in)
   * For validating the input of addautoresponder form
   */
function validateModifyAutoResponderInput(form_id)
{
    form = $(form_id);
    form_elem_array = form.elements ;
    for(i=0; i < form_elem_array.length; i++) {
        f = form_elem_array[i] ;
        if( f.id == "modifyAuto_start_date") {
            start_date = f.value;
        }
        else if( f.id == "modifyAuto_end_date") {
            end_date = f.value;
        }
        else if( f.id == "modifyAuto_subject") {
            subject = f.value;
        }
        else if( f.id == "modifyAuto_message") {
            message = f.value;
        }
    }

    invalid = false;
    error_message = "";
    //check date formats.
    if (start_date == "" ||  !isDate(start_date) )
    {
        invalid = true;
        error_message = "Start Date is entered incorrectly. Please enter it as dd-mm-yyyy";
    }
    else if (end_date == "" || !isDate(end_date) )
    {
        invalid = true;
        error_message = "End Date is entered incorrectly. Please enter it as dd-mm-yyyy";
    }
    else if(subject=="" && message=="") {
        invalid = true;
        error_message="Both Subject & message are empty. Please enter atleast one of them"
    }

    if (invalid)
    {
        refreshNotices(error_message);
        return false;
    }
    return true;
}

/**
   * Author : Ritesh Sinha(sinha.riteshk@limespot.co.in)
   * For validating the input of addautoresponder form
   */
function validateAddAutoResponderInput(form_id)
{
    form = $(form_id)
    form_elem_array = form.elements ;
    for(i=0; i < form_elem_array.length ; i++) {
        f = form_elem_array[i] ;
        if( f.id == "addAuto_start_date") {
            start_date = f.value;
        }
        else if( f.id == "addAuto_end_date") {
            end_date = f.value;
        }
        else if( f.id == "addAuto_subject") {
            subject = f.value;
        }
        else if( f.id == "addAuto_message") {
            message = f.value;
        }
    }

    invalid = false;
    error_message = "";
    //check date formats.
    if (start_date == "" ||  !isDate(start_date) )
    {
        invalid = true;
        error_message = start_date == "" ? "Start Date can't be left blank." : "Start Date is entered incorrectly. Please enter it as dd-mm-yyyy";
    }
    else if (end_date == "" || !isDate(end_date) )
    {
        invalid = true;
        error_message = end_date == "" ?  "End Date can't be left empty." :"End Date is entered incorrectly. Please enter it as dd-mm-yyyy";
    }
    else if(subject=="" && message=="") {
        invalid = true;
        error_message="Both Subject & message are empty. Please enter atleast one of them"
    }

    if (invalid)
    {
        refreshNotices(error_message);
        return false;
    }
    return true;
}

/**
   * Author : Ritesh Sinha(sinha.riteshk@limespot.co.in)
   * Helper method for date validation
   */
function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

/**
   * Author : Ritesh Sinha(sinha.riteshk@limespot.co.in)
   * Helper method for date validation
   */
function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

/**
   * Author : Ritesh Sinha(sinha.riteshk@limespot.co.in)
   * Helper method for date validation
   */
function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
/**
   * Author : Ritesh Sinha(sinha.riteshk@limespot.co.in)
   * Helper method for date validation
   */
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {
            this[i] = 30
        }
        if (i==2) {
            this[i] = 29
        }
    }
    return this
}

/**
   * Author : Ritesh Sinha(sinha.riteshk@limespot.co.in)
   * For validating date (tests for a valid date in form dd-mm-yyyy)
   */
function isDate(dtStr){
    var dtCh= "-";
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strDay=dtStr.substring(0,pos1)
    var strMonth=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
        return false
    }
    if (strMonth.length<1 || month<1 || month>12){
        return false
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day >
        daysInMonth[month]){
        return false
    }
    if (strYear.length != 4 || year==0){
        return false
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        return false
    }
    return true
}

/**
   * Author : Ritesh Sinha(sinha.riteshk@limespot.co.in)
   * For putting the autoresponder popups at appropriate position
   */
//	function callFloatAutoRespond(pWidth)
//	{
//		var winL = (screen.width - pWidth) / 2;
//		var winH = "90";
//
//
//		var floatingDiv = document.getElementById("floatingDiv");
//		var floatContainer = document.getElementById("floatContainer");
//		var floatContent = document.getElementById("floatContent");
//
//		floatingDiv.style.display="";
//		floatContainer.style.display="";
//		floatContent.style.display="";
//
//		floatContainer.style.width = pWidth;
//
//		floatContainer.style.left=winL;
//		floatContainer.style.top=winH;
//
//		var quota = document.getElementById("quota");
//		var forwarding = document.getElementById("forwarding");
//		var alias = document.getElementById("alias");
//		var autoRespond = document.getElementById("autoRespond");
//		var processQuota = document.getElementById("processQuota");
//
//
//		quota.style.display="none";
//		forwarding.style.display="none";
//		alias.style.display="none";
//		autoRespond.style.display="";
//
//		processQuota.style.display="none";
//	}


function checkBackUp(form_id){
    if(!checkFields(form_id) || !checkNumberFields(form_id)
        || !billing_checks()){
        return false;
    }
    return true;
}

//TODO : Factor out the common code in the following two functions to
// create another function.
/*
 * Refactored by Chandranshu
 * This function now accepts the id of the text box to be used
 *  for a domain name or similar inputs that may or may not have
 *  the TLDs typed in.
 */

function correct_domain_format(value){
    domain_text = value;
    domain_text = domain_text.replace(/^\s+|\s+$/g,"") ;
    reg = /^[\w\d][\w\d\-\.]*[\w\d]$/;
    return (!((!(reg.test(domain_text))||(/_/.test(domain_text))) || (/^(xn--)/.test(domain_text))))
}

function domain_text_verify(domain_text_box_id) {
    domain_text = $(domain_text_box_id).value;
    domain_text = domain_text.replace(/^\s+|\s+$/g,"") ;
    reg = /^[\w\d][\w\d\-\.]*[\w\d]$/;
    if (!(reg.test(domain_text))||(/_/.test(domain_text))) {
        return domainNameError();
    }
    if (domain_text.length > 63){
        return domainNameError(messageList.domainLong);
    }
    if (/^(xn--)/.test(domain_text)){
        return domainNameError(messageList.domainInternationalError);
    }
    return true;
}


function transfer_verify(domain_id, auth_code_id) {
    domain_text = $(domain_id).value;
    domain_text = domain_text.replace(/^\s+|\s+$/g,"") ;
    reg = /^[\w\d][\w\d\-\.]*[\w\d]$/;
    if (!(reg.test(domain_text))||(/_/.test(domain_text))) {
        return domainNameError();
    }
    if (/^(xn--)/.test(domain_text)){
        refreshNotices("We do not support international domain names");
        return false;
    }
    auth_code_length = $(auth_code_id).value.length;
    if (auth_code_length < 6 || auth_code_length > 16) {
        refreshNotices("Authorization Code should be from 6 to 16 characters");
        return false;
    }
    return true;
}
addLoadEvent(prepareInputsForDescription);

function createCookie(name,value) {
    document.cookie = name+"="+value+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}


function toggleSelect(selectorId,className){
    boxes = $$("." + className);
    state = $(selectorId).checked
    for(var i=0;i<boxes.length;i++){
        boxes[i].checked = state ;
    }
}
function validate_home_dir_form(form_id, home_dir)
{
    home_dir = trim(home_dir);
    if (home_dir.length!=0 )
        return dirtyForm(form_id) && validate_hosting_path(home_dir);
    else
        return dirtyForm(form_id)
}

function removeCharacters(str) {
    re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
    return str.replace(re, "");
}

function validate_hosting_path(path){
    path=trim(path);
    var re = /^[a-zA-Z0-9_\/\.-]+$/;
    var re1 = /\.\./;
    var match = re.exec(path);

    if(path.length == 0){
        refreshNotices("File/Directory name should not be empty.");
        return false;
    }
    if(match == null){
        refreshNotices("Invalid File/Directory name. Only alpahbet, numbers, - . and _ are allowed. Additionally, you can use '/' to denote subdirectories. White spaces, .. and other special characters are not allowed.");
        return false;
    }
    var match1 = re1.exec(path)
    if(match1 !=null ){
        refreshNotices("Path should not contain '..'");
        return false;
    }
    return true;
}
function validate_path(path)
{
    if(path.length == 0){
        refreshNotices("Name cannot be blank");
        return false;
    }else{
        var re = /^[a-zA-Z0-9_\/\.-]+$/;
        var re1 = /\.\./;
        var match = re.exec(path);
        if(match == null){
            refreshNotices("Only alpahbets, numbers, - . and _ are allowed. White spaces and other special characters are not allowed.");
            return false;
        }
        var match1 = re1.exec(path)
        if(match1 !=null ){
            refreshNotices("Path should not contain '..' ");
            return false;
        }
    }
    return true;
}

function validate_password_confirmation(password, confirm_password){
    if(password != confirm_password){
        refreshNotices("Confirmed password did not match");
        return false;
    }else{
        if(password.length==0){
            refreshNotices("Empty password not allowed");
            return false;
        }else{
            if(password.length<6){
                refreshNotices("Password should be atleast 6 characters long.");
                return false;
            }
        }
    }
    return true;
}


function validate_create_ftp_user(username,password, confirm_password, home_dir){
    home_dir = trim(home_dir);
    var msg = "" ;
    var flag = true;
    if(username.length==0){
        msg += "Empty username. <br><br>";
        flag = false;
    }else{
        var re = new RegExp("^(/)?([a-zA-Z0-9-_]+)$");
        var match = re.exec(username);
        if(match == null){
            msg += ("Invalid user name. Please use only letters, numbers and '_' .<br><br>");
            flag = false;
        }
    }
    if(password.length>16){
        msg += "Password cannot be greater than 16 characters. <br><br>";
        flag = false;
    }else{
        if(password.length<6){
            if(password.length == 0){
                msg += "Password cannot be empty <br><br>";
                flag = false;
            }else{
                msg += "Password too short, please use atleast 6 characters <br><br>";
                flag = false;
            }
        }
    }

    if(password != confirm_password){
        msg += "Password confirmation did not match. <br><br>";
        flag = false;
    }

    if(home_dir.length != 0){
        if (!validate_hosting_path(home_dir)){
            msg += "Invalid File/Directory name. Only letters, numbers, - . and _ are allowed. Additionally, you can use '/' to denote subdirectories. White spaces, .. and other special characters are not allowed.<br><br>";
            flag = false;
        }
    }

    if(flag == false){
        refreshNotices(msg);
        return false;
    }
    return true;
}

function activate_rename_div(filename, dirname, website)
{
    var renameForm = '<input id="new_file_name_'+ filename +'" type="text" size="20" value="' + filename + '" name="new_file_name_'+ filename +'" onkeypress="if(event.keyCode==13){submit_rename_form('+ "'"+ filename + "','" + dirname + "'," + website + ');return false;}">';
    renameForm += ' <input type="image" src="/images/btn_rename.gif" align="absmiddle" value="Rename" onClick="submit_rename_form('+ "'"+ filename + "','" + dirname + "'," + website + ');return false;">';
    renameForm += ' <input class="btnCancelSmall" type="button" onclick="cancel_rename('+ "'"+ filename + "'" + ');" value="Cancel">';

    $(filename + '_edit').innerHTML = renameForm;
    $(filename + '_val').hide();
    $(filename + '_edit').show();
    $('new_file_name_' + filename).focus();

    return renameForm;
}

function cancel_rename(filename)
{
    $(filename + '_edit').innerHTML = "";
    $(filename + '_edit').hide();
    $(filename + '_val').show();
}

function submit_rename_form(filename, dirname, website)
{
    var f = $('rename_form');
    f.style.display = 'none';

    var new_name_txt_field = $('new_file_name');
    var old_name_field = $('file_name_existing');
    new_name_txt_field.value = $('new_file_name_' + filename).value;
    old_name_field.value = filename;
    if(validate_rename_path(new_name_txt_field.value))
        f.submit();
}

function validate_rename_path(path){
    if(validate_path(path)){
        var re = /\//;
        var match = re.exec(path)
        if(match !=null ){
            refreshNotices("New name can not contain '/'");
            return false;
        }
        else
            return true;
    }
    else return false;
}

function hideDbTexts(){

    $('db_list_text').hide();
    $('user_list_text').hide();
    $('create_db_text').style.display="none";
    $('create_user_text').style.display="none";

}

function showDbLinks(){
    $('db_list_link').show();
    $('user_list_link').show();
    $('create_db_link').style.display="";
    $('create_user_link').style.display="";
}

function activateDbTab(){
    $('mainTable').show();
    $('userlist').hide();
    $('usertext').hide();
    $('create_new_db').hide();
    $('create_db_user').hide();
    $('dblist').show();
    $('dbtext').show();
    hideDbTexts();
    showDbLinks();
    $('db_list_link').hide();
    $('db_list_text').show();
}

function activateDbUserTab(){
    $('mainTable').show();
    $('dblist').hide();
    $('dbtext').hide();
    $('create_new_db').hide();
    $('create_db_user').hide();
    $('usertext').show();
    $('userlist').show();
    hideDbTexts();
    showDbLinks();
    $('user_list_link').hide();
    $('user_list_text').show();
}

function activateCreateDbUserTab(){
    $('mainTable').hide();
    $('create_new_db').hide();
    $('create_db_user').show();
    $('username').focus();
    hideDbTexts();
    showDbLinks();
    $('create_user_link').style.display="none";
    $('create_user_text').style.display="";
}

function activateCreateDbTab(){
    $('mainTable').hide();
    $('create_db_user').hide();
    $('create_new_db').show();
    $('dbname').focus();
    hideDbTexts();
    showDbLinks();
    $('create_db_link').style.display="none";
    $('create_db_text').style.display="";
}

function highLightDbDiv(id){
    $('change_password').hide();
    if(id == "dblist")
        activateDbTab();
    if(id == "userlist")
        activateDbUserTab();
    if(id == "create_new_dbuser_link")
        activateCreateDbUserTab();
    if(id == "create_new_db_link")
        activateCreateDbTab();
    return false;
}

function showDatabaseOptions(){
    $('dbname').disabled = false;
    $('dbuser').disabled = false;
    $('dbpasswd').disabled = false;
    $('dbpasswd_confirm').disabled = false;
    $('database_options').style.display='';
}

function hideDatabaseOptions(){
    $('dbname').disabled = true;
    $('dbuser').disabled = true;
    $('dbpasswd').disabled = true;
    $('dbpasswd_confirm').disabled = true;
    $('database_options').style.display='none';
}

function populateBlogInstallForm(){
    var url;
    if($('public_account') && $('public_account').checked){
        url = $('public_domain_name').value + ".limedemo.com";
    }
    if($('local_account') && $('local_account').checked){
        url = $('local_account_domain').value;
    }
    if ($("outside_account").checked){
        url = $('outside_domain_name').value;
    }
    url = url.replace(new RegExp(/^http\:\/\/|^https\:\/\/|^ftp\:\/\//i),"");
    url = url.replace(new RegExp(/^www\./i),"");
// closeFloatsCart('domainName');
}
function populatepasswordfield(div,passwd_div){
    passwd_div.value = div.value
}

function subDomain(url) {
    // IF THERE, REMOVE WHITE SPACE FROM BOTH ENDS
    url = url.replace(new RegExp(/^\s+/),""); // START
    url = url.replace(new RegExp(/\s+$/),""); // END

    // IF FOUND, CONVERT BACK SLASHES TO FORWARD SLASHES
    url = url.replace(new RegExp(/\\/g),"/");

    // IF THERE, REMOVES 'http://', 'https://' or 'ftp://' FROM THE START
    url = url.replace(new RegExp(/^http\:\/\/|^https\:\/\/|^ftp\:\/\//i),"");

    // IF THERE, REMOVES 'www.' FROM THE START OF THE STRING
    url = url.replace(new RegExp(/^www\./i),"");

    // REMOVE COMPLETE STRING FROM FIRST FORWARD SLASH ON
    url = url.replace(new RegExp(/\/(.*)/),"");

    // REMOVES '.??.??' OR '.???.??' FROM END - e.g. '.CO.UK', '.COM.AU'
    if (url.match(new RegExp(/\.[a-z]{2,3}\.[a-z]{2}$/i))) {
        url = url.replace(new RegExp(/\.[a-z]{2,3}\.[a-z]{2}$/i),"");

    // REMOVES '.??' or '.???' or '.????' FROM END - e.g. '.US', '.COM', '.INFO'
    } else if (url.match(new RegExp(/\.[a-z]{2,4}$/i))) {
        url = url.replace(new RegExp(/\.[a-z]{2,4}$/i),"");
    }

    // CHECK TO SEE IF THERE IS A DOT '.' LEFT IN THE STRING
    var subDomain = (url.match(new RegExp(/\./g))) ? true : false;

    return(subDomain);
}

function trim(a){
    a = a.replace(/^\s+/, '');
    a = a.replace(/\s+$/, '');
    return a;
}
function showCreateDBUserDiv(){
    $('selectDBUser').hide();
    $('createDBUser').show();
    $('dbusername').disabled=false;
    $('dbusername').focus();
    if($('dbuser'))
        $('dbuser').disabled=true;
}
function hideCreateDBUserDiv(){
    $('createDBUser').hide();
    $('selectDBUser').show();
    $('dbusername').disabled=true;
    if($('dbuser')){
        $('dbuser').disabled=false;
        $('dbuser').focus();
    }
}

function showCreateDBDiv(){
    $('selectDB').hide();
    $('createDB').show();
    $('dbnameTxt').disabled=false;
    $('dbnameTxt').focus();
    if($('dbname'))
        $('dbname').disabled=true;
}
function hideCreateDBDiv(){
    $('createDB').hide();
    $('selectDB').show();
    $('dbnameTxt').disabled=true;
    if($('dbname')){
        $('dbname').disabled=false;
        $('dbname').focus();
    }
}

function hide_subdomain_input(){
    $$('input[class="demo"]').each(function(s) {
        s.disabled = true;
    });
    $('demo_input_div').hide();
}

function hide_userowned_input(){
    $$('input[class="userowned"]').each(function(s) {
        s.disabled = true;
    });
    $('userdomain_input_div').hide();
}

function hide_domainsearch_input(){
    $('domain_search_box').disabled = true;
    $('tld_select_hosting').disabled = true;
    $('search_domain').disabled = true;
    $('newdomain_input_div').hide();
    if($('boxDBL'))
        $('boxDBL').hide();
}

function changeDomainType(){
    var selected_app = $('app_id').options[$('app_id').selectedIndex].id;
    hide_subdomain_input();
    hide_userowned_input();
    hide_domainsearch_input();
    if($('domain_type_subdomain').checked){
        $('subdomain').disabled = false;
        //      $('setup_demo_blog').disabled = false;
        //$('setup_demo_customize').disabled = false;
        $$('#demo_'+ selected_app + '_partial input[class="demo"]').each(function(s) {
            s.disabled = false;
        });

        $('demo_input_div').show();
        $('subdomain').focus();
        // unhide the continue button and enable it
        $('continue_not_new').disabled = false;
        $('continue_not_new').show();
    }

    if($('domain_type_userowned').checked){
        $('user_domain').disabled = false;
        //     $('setup_user_blog').disabled = false;
        //   $('setup_user_customize').disabled = false;
        $$('#userowned_'+ selected_app + '_partial input[class="userowned"]').each(function(s) {
            s.disabled = false;
        });

        $('userdomain_input_div').show();
        $('user_domain').focus();
        $('continue_not_new').disabled = false;
        $('continue_not_new').show();
    }

    if($('domain_type_new').checked){
        $('domain_search_box').disabled = false;
        $('tld_select_hosting').disabled = false;
        $('search_domain').disabled = false;
        $('newdomain_input_div').show();
        $('domain_search_box').focus();
        if($('boxDBL'))
            $('boxDBL').blindDown();
        $('continue_not_new').disabled = true;
        $('continue_not_new').hide();
    }
}

function show_explanation(show_div,hide_class){
    explanations = $$("."+hide_class);
    for(i=0;i<explanations.length;i++)
    {
        explanations[i].style.display="none";
    }
    $(show_div+"_text").style.display="";
}

function showHideInputDivs(apps_combo_box)
{
    var selected_app = apps_combo_box.options[apps_combo_box.selectedIndex].id;
    //show_explanation(selected_app,'explanation');
    // hide all application specific inputs
    $$('div[class="partials_div"]').each(function(s) {
        s.hide();
    });
    changeDomainType();

    $('demo_'+ selected_app + '_partial').show();
    $('userowned_'+ selected_app + '_partial').show();
}

function ValidateNameAndIp(name_id,ip_id){
    subdomain = $(name_id).value
    var reg = /^([\w\d]([\w\d\-]*[\w\d])?\.)*[\w\d]([\w\d\-]*[\w\d])?$/ ;
    valid_subdomain = !(!reg.test(subdomain) || /_/.test(subdomain));
    if(!valid_subdomain){
        refreshNotices(subdomain + " is not a valid name.");
        return false;
    }
    else
        return validateIPAddr($(ip_id).value.strip());
}

function confirm_mailinglist_delete(){
    var form_id = $('form_id').value;
    var form_name = 'delete_listuser_' + form_id;
    $(form_name).submit();
}

function show_mailinglist_confirmation(i,username){
    $('form_id').value = i;
    $('warning').innerHTML = 'Are you sure you want to delete user ' + username + ' ?';
    callFloats('700','userDeleteFromMailingList');
}


function showAddNewUser(obj){
    var showaddlist = $('showaddlist');
    var adduser = $('adduser');

    showaddlist.style.display='none';
    adduser.style.display='';
}


function hideAddNewUser(obj){
    var showaddlist = $('showaddlist');
    var adduser = $('adduser');
    showaddlist.style.display='';
    adduser.style.display='none';
}

function showMe (it, box) {
    var vis = (box.checked) ? "block" : "none";
    document.getElementById(it).style.display = vis;
}

function website_details(website_div_id,website_row_id){    
    elements = document.getElementsByClassName('ctrl_tr_over padtop_bottom')
    row_elements = document.getElementsByClassName('web_row_details')
    for(i=0;i<elements.length;i++){
        elements[i].setAttribute("class", 'ctrl_tr_on');
    }
    for(i=0;i<row_elements.length;i++){
        row_elements[i].hide();
    }
    $(website_row_id).setAttribute("class", 'ctrl_tr_over padtop_bottom');
    $(website_div_id).show();
}

function toggle_plan_details(plan_details_div_id,arrow1_div_id,arrow2_div_id){
    div_element = $(plan_details_div_id);
    arrow1 = $(arrow1_div_id);
    arrow2 = $(arrow2_div_id);
    
    if(div_element.style.display == 'none')
        div_element.style.display = "";
    else
        div_element.style.display = 'none';
    if(arrow1.style.display == 'none')
        arrow1.style.display = "";
    else
        arrow1.style.display = 'none';
    if(arrow2.style.display == 'none')
        arrow2.style.display = "";
    else
        arrow2.style.display = 'none';
    elements = document.getElementsByClassName('rename')
    for(i=0;i<elements.length;i++){
        elements[i].hide();
    }
}
function toggle_rename_div(div_id){
    elements = document.getElementsByClassName('rename')
    for(i=0;i<elements.length;i++){
        elements[i].hide();
    }
    $(div_id).show();

}




// substr_count

function substr_count (haystack, needle, offset, length)
{
    var pos = 0, cnt = 0;

    haystack += '';
    needle += '';
    if (isNaN(offset)) {
        offset = 0;
    }
    if (isNaN(length)) {
        length = 0;
    }
    offset--;

    while ((offset = haystack.indexOf(needle, offset+1)) != -1){
        if (length > 0 && (offset+needle.length) > length){
            return false;
        } else{
            cnt++;
        }
    }

    return cnt;
}

// test_ipv4
// Test for a valid dotted IPv4 address

function test_ipv4(ip)
{
    var match = ip.match(/(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|255[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/);
    return match != null;
}

// test_ipv6

function validateIPv6Addr(ip)
{
    // Test for empty address
    if (ip.length<3)
    {
        return ip == "::";
    }

    // Check if part is in IPv4 format
    if (ip.indexOf('.')>0)
    {
        lastcolon = ip.lastIndexOf(':');

        if (!(lastcolon && test_ipv4(ip.substr(lastcolon + 1))))
        {
            return false;
        }

        // replace IPv4 part with dummy
        ip = ip.substr(0, lastcolon) + ':0:0';
    }

    // Check uncompressed
    if (ip.indexOf('::')<0)
    {
        var match = ip.match(/^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i);
        if (match != null){
            return true;
        }
        else
        {
            return false;
        }

    }

    // Check colon-count for compressed format
    if (substr_count(ip, ':')< 8)
    {
        var match = ip.match(/^(?::|(?:[a-f0-9]{1,4}:)+):(?:(?:[a-f0-9]{1,4}:)*[a-f0-9]{1,4})?$/i);
        if (match != null){
            return true;
        }
        else
        {
     
            return false;
        }
    }

    return true;
}

//close a div
function closeDiv(name) {
    $(name).style.display ='none';
}

//open a div
function openDiv(name) {
    $(name).style.display = '';
}

function domainNameError(string)
{
    if (string != null)
        refreshNotices(string);
    else
        refreshNotices(messageList.domainError);
    return false;
}

function Ssl() {
    this.disableInputsForDiv = function(divId, disable){
        $$('div#'+ divId + ' input').each(function(elem) {
            elem.disabled = disable;
        });
        $$('div#'+ divId + ' textarea').each(function(elem) {
            elem.disabled = disable;
        });
        $$('div#'+ divId + ' select').each(function(elem) {
            elem.disabled = disable;
        });
    }

    this.showAllContacts = function (){
        var divsToShow = ['billing_contact', 'admin_contact']
        for(i=0;i<2;i++){
            this.disableInputsForDiv(divsToShow[i]+'_div', false);
            $(divsToShow[i]+'_head').show();
            $(divsToShow[i]+'_div').show();
        }
    }

    this.hideAllContacts = function (){
        var divsToShow = ['billing_contact', 'admin_contact']
        for(i=0;i<2;i++){
            $(divsToShow[i]+'_head').hide();
            $(divsToShow[i]+'_div').hide();
            this.disableInputsForDiv(divsToShow[i]+'_div', true);
        }
    }

    this.verifyCSRForm = function (){
        var validator = new Validation('generate_csr', {onSubmit : false});
        validator.reset();
        if (validator.validate()){
            callFloatsCart('700','generate_csr_confirmation',[]);
            scroll(0,0);
        }
    }

}
