// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

//Function to uncheck all the check boxes when the customer listing page loads
//Also empties the search box

function textCounter(field, maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	}

function checkboxDisable(){
    var checkedBoxes = document.getElementById('myform').childNodes;
    if ($(checkedBoxes)) {
        for (var i = 0; i < checkedBoxes.length; i++) {
            checkedBoxes[i].checked = false;
            //document.getElementById('search_string').value = '';
        
        }
    }
    
}


function refresh_agenda_block(app_ids){
    for (i = 0; i < app_ids.length; i++) {
        if ($('app_date_' + app_ids[i])) {
            $('app_date_' + app_ids[i]).removeClassName('requested_appt');
        }
        if ($('app_custname_' + app_ids[i])) {
            $('app_custname_' + app_ids[i]).removeClassName('requested_appt');
        }
    }
}

function callColorPicker(){

    aa = $('color').color.showPicker();
    //document.getElementById('color').color.showPicker();
}

function replace_testimony(parent_id, replaced_with, flag){
    $(parent_id).update(replaced_with.innerHTML);
    if (flag) {
        Element.show('create_service_group');
        $(parent_id).id = replaced_with.id;
    }
    
}

// Function to check if any help balloon popup is clicked on the page
function find_help_on_page(event, message_text){
    if (!$('balloon')) {
        balloon.showTooltip(event, message_text, 1);
        
    }
}

function agree_check_box_error(name_of_class){
    if ($('agree_check_box')) 
        $('agree_check_box').className = name_of_class;
    if ($('agree_check_box_wait')) 
        $('agree_check_box_wait').className = name_of_class;
    
}

function hideCreateAppointment(form_name, label){
    _form_name = form_name;
    _label = label;
    if (_dirty_bit == true) {
        jQuery.prompt('Are you sure you want to cancel your changes?', {
            buttons: {
                Ok: false,
                Cancel: true
            },
            top: 200,
            callback: closeEventBlock
        });
    }
    else {
        unsetDirtyBit();
        //RedBox.close();
        toggle_visibility_and_close();
    }
    
}

function closeEventBlock(btn){
    if (btn) {
        toggle_visibility_of_fields('show');
        return false;
    }
    else {
        unsetDirtyBit();
        //RedBox.close();
        toggle_visibility_and_close();
    }
    
    
}

function checklength(element){
    if (element == 'password') {
        if ($('password').value.length > 10) {
            $('password').value = $('password').value.substring(0, 10);
        }
    }
    else {
        if ($('email_address').value.length > 50) {
            $('email_address').value = $('email_address').value.substring(0, 50);
        }
    }
}

function hideChangeAppointment(form_name, label){
    _form_name = form_name;
    _label = label;
    if (($('target_url') != null) && (_dirty_bit == true)) {
        jQuery.prompt('Are you sure you want to navigate away from this page? <br><br> You have made changes to the page. Are you sure you want to exit without saving?', {
            buttons: {
                Ok: false,
                Cancel: true
            },
            top: 200,
            callback: hidePopup
        });
    }
    else {
        unsetDirtyBit();
        //RedBox.close();
        toggle_visibility_and_close();
    }
    
}

function hidePopup(btn){
    if (btn) {
        toggle_visibility_of_fields('show');
        return false;
    }
    else {
        unsetDirtyBit();
        //RedBox.close();
        toggle_visibility_and_close();
    }
}

function getInternetExplorerVersion()// Returns the version of Windows Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null) 
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

function fill_end_timeForCreate(t){
    //    if (t != "Custview") {
    if ($('service').value != "") {
        for (i = 0; i < service_arr.length; i++) {
            var each_service = new Array();
            each_service = service_arr[i];
            var k;
            var service_id;
            for (k = 0; k < each_service.length; k++) {
                service_id = each_service[0];
                if (service_id == $('service').value) {
                    service_duration = each_service[2];
                    populateEndTime(service_duration);
                    break;
                }
            }
        }
    }
    else {
        if ($('end_time').innerHTML != "") 
            $('end_time').innerHTML = "";
    }
    //    }
}

function ask_for_new_customer(msg){
	if (document.getElementById('cust')) {
		cust_ele = document.getElementById('cust').getElementsByTagName('input');
		if ((cust_ele[0].value == 'Select a customer...') || ($('addnewcustomer').checked == true)) {
			return true;
		}
		if (cust_ele[0].value != '' && cust_ele[1].value == '') {
			_cust_name = cust_ele[0].value;
			jQuery.prompt(msg.replace(/&/, cust_ele[0].value), {
				buttons: {
					Yes: true,
					No: false
				},
				callback: show_new_customer_form
			});
		}
		else {
			return true;
		}
	}
	return true;
}

function show_new_customer_form(btn){
    if (btn) {
        cust_name_array = _cust_name.split(' ');
        $('addnewcustomer').checked = true;
        togglecustomerInfo('yes');
        $('customer_first_name').value = cust_name_array[0];
        cust_name_array.splice(0, 1);
        $('customer_last_name').value = cust_name_array.join(' ');
    }
    return false;
}

function reset_view_elements(elemnet_id){
    if ($(elemnet_id) != null) {
        Element.remove(elemnet_id);
    }
    Element.show("create_service_group");
}

function check_for_already_open_form(table_id, add_link_id, action, token){
    if ($(table_id).getElementsByTagName("input").length == 0) {
        Element.hide(add_link_id);
        new Ajax.Request(action, {
            asynchronous: true,
            evalScripts: true,
            parameters: 'authenticity_token=' + encodeURIComponent(token)
        });
        return false;
    }
    else {
        jQuery.prompt('Please save the already opened form.');
        return false;
    }
    
}

function check_for_open_form_and_back(table_id, add_link_id, action, token){
    if ($(table_id).getElementsByTagName("input").length == 0) {
        window.location.href = action;
    }
    else {
        jQuery.prompt('Please save the already opened form.');
        return false;
    }
    
}

function remove_current_row(row_id, msg, table_id, from){
    _row_id = row_id;
    _table_id = table_id
    if (_dirty_bit == 1) {
        if (from == 'service') {
            jQuery.prompt(msg, {
                buttons: {
                    Ok: true,
                    Cancel: false
                },
                callback: remove_service_row
            });
        }
        else {
            jQuery.prompt(msg, {
                buttons: {
                    Yes: true,
                    No: false
                },
                callback: remove_c_row
            });
        }
    }
    else {
		 if (from == 'service') 
		 	remove_service_row('true');
		 else
	        remove_c_row('true');
    }
    
}

function remove_c_row(btn){
    if (btn) {
        $(_table_id).deleteRow($(_row_id).rowIndex);
        unsetDirtyBit();
        reset_view_elements();
    }
    else {
        return false;
    }
}

function remove_service_row(btn){
	
    if (btn) {
        $(_table_id).deleteRow($($(_row_id).parentNode).rowIndex);
        unsetDirtyBit();
        reset_view_elements();
    }
    else {
        return false;
    }
}


function submit_group_form(form_element){
    $('service_group_form').request();
}

function cancelChanges(url){
    _new_link = url;
    jQuery.prompt("Are you sure you want to cancel your changes?", {
        buttons: {
            Yes: true,
            No: false
        },
        top: 200,
        callback: hideApptDiv_cust
    })
}

function hideApptDiv_cust(btn){
    if (btn) {
        window.location.href = _new_link;
    }
    
}

function removing_row(table_id, first_row_id, second_row_id, row){
    $(table_id).deleteRow($(first_row_id).rowIndex);
    $(table_id).deleteRow($(second_row_id).rowIndex);
    var x = document.getElementsByTagName("input");
    var y = document.getElementsByClassName("fieldWithErrors");
    
    if (x.length <= 4) {
        id = 'savecancel';
        if ($(id) != null) 
            if ($(id).style.display == "") 
                $(id).style.display = "none";
    }
    
    if (y.length < 1) {
        if ($('error_msg_tag') != null) 
            $('error_msg_tag').innerHTML = '';
    }
    return false;
}

function removerow(row, table_id, first_row_id, second_row_id){
    if (table_id == "staff_table") {
        if ($(first_row_id)) 
            $(table_id).deleteRow($(first_row_id).rowIndex);
        if ($(second_row_id)) 
            $(table_id).deleteRow($(second_row_id).rowIndex);
    }
    else 
        $(table_id).deleteRow(row.parentNode.parentNode.rowIndex);
    
    
    var x = document.getElementsByTagName("input");
    var y = document.getElementsByTagName("div");
    var i = 0;
    var cnt = 0;
    while (element = y[i++]) {
        if (element.className == "fieldWithErrors") {
            cnt = cnt + 1;
        }
    }
    if (x.length <= 4) {
        id = 'savecancel';
        if ($(id) != null) 
            if ($(id).style.display == "") 
                $(id).style.display = "none";
    }
    
    if (cnt == 0) {
        if ($('error_msg_tag') != null) 
            $('error_msg_tag').innerHTML = '';
    }
    return false;
}

function savecancel(){
    var id = 'savecancel';
    var flag = 'true';
    if ($(id) != null) 
        if ($(id).style.display == "none") 
            $(id).style.display = "";
    return false;
    
}

function deleteservice(){
    new Ajax.Request('/services/destroy/7', {
        asynchronous: true,
        evalScripts: true,
        parameters: 'authenticity_token=' + encodeURIComponent('/rm25ieQiH5PzH9D75SYqIf31m+3fvlC+kuxZWorHAA=')
    });
    return false;
}

function sign_out_window(dirty_bit_msg, sign_out_msg, url){
    _link = url;
    if (_dirty_bit == true) {
        jQuery.prompt(dirty_bit_msg, {
            buttons: {
                Ok: true
            },
            top: 200
        });
    }
    else {
        jQuery.prompt(sign_out_msg, {
            buttons: {
                Yes: true,
                No: false
            },
            top: 200,
            callback: sign_out
        });
    }
}

function sign_out(btn){
    if (btn) {
        window.location.href = _link;
    }
}

function move_forward(btn){
    if (btn) {
        $('target_url').value = _action;
        if (document.formone) {
            document.formone.submit();
        }
        else 
            if (document.webbio) {
                document.webbio.submit();
                window.location.href = _link;
            }
            else {
                form_id = $('form_id').value;
                $(form_id).request();
            }
        return false;
    }
    else {
        window.location.href = _link;
    }
}

function utilization_view(url_address, token){
    var staff_id = "";
    staff_id = document.getElementById('dp_staff_id').value;
    var utilization_view = document.getElementById('view_type').value;
    asynchronous: true, new Ajax.Updater('request_container_utilization', url_address + "/?staff_id=" + staff_id + "&utilization_view=" + utilization_view, {
        evalScripts: true,
        onComplete: function(request){
        },
        parameters: 'authenticity_token=' + encodeURIComponent(token)
    });
}

function changeView(action){
    _action = action;
    _link =  window.location.protocol + "//" + window.location.host + action;
    //alert(_link);
    if (($('target_url') != null) && (_dirty_bit == true)) {
        jQuery.prompt('Are you sure you want to navigate away from this page? <br><br> You have made changes to the page. Are you sure you want to exit without saving?', {
            buttons: {
                Ok: false,
                Cancel: true
            },
            focus: 0,
            top: 200,
            callback: showResult
        })
    }
    else 
        if (($('target_url') != null) && (ff_bit == true)) {
            jQuery.prompt('Are you sure you want to cancel the message?', {
                buttons: {
                    Yes: false,
                    No: true
                },
                focus: 0,
                top: 200,
                callback: showResult
            })
        }
        else {
            window.location.href = _link;
        }
}

function saveAndRedirectsToTestimony(action) {
    _action = action;
    _link =  window.location.protocol + "//" + window.location.host + action;
    if (($('target_url') != null) && (_dirty_bit == true)) {
        $('target_url').value = action;
        checkOpenTimingsContentForWordLimit('save');
    }
    else { 
       window.location.href = _link;
    }
}

function checkChanges(action){
    _action = action;
    if ((($('target_url') != null) && _dirty_bit == true)) {
        jQuery.prompt('Are you sure you want to navigate away from this page? <br><br> You have made changes to the page. You need to save the changes before leaving this screen.', {
            buttons: {
                Yes: true,
                No: false
            },
            focus: 0,
            top: 200,
            callback: saveChanges
        })
    }
    else 
        window.location.href = _action;
}

function saveChanges(btn){
    if (btn) {
		$('target_url').value = _action;
		check_mobile_for_active_staff();
    }
    
}

function showConflict(msg, new_staff, new_service, new_customer, new_appt_date, new_start_time, new_end_time, staff_notes){
    _new_staff = new_staff;
    _new_service = new_service;
    _new_customer = new_customer;
    _new_appt_date = new_appt_date
    _new_start_time = new_start_time
    _new_end_time = new_end_time
    _staff_notes = staff_notes
    jQuery.prompt(msg, {
        buttons: {
            Yes: true,
            No: false
        },
        top: 200,
        callback: getResponse
    })
}

function getResponse(btn){
    if (btn) {
        var url =  window.location.protocol + "//" + window.location.host + "/appointments/override/?staff=" + _new_staff + "&service=" + _new_service + "&customer=" + _new_customer + "&appt_date=" + _new_appt_date + "&start_time=" + _new_start_time + "&end_time=" + _new_end_time + "&s_notes=" + _staff_notes;
        new Ajax.Request(url, {
            method: 'get'
        });
    }
    else {
        return false;
    }
}

function conflictTime(msg, url){
    _urlBlock = url;
    jQuery.prompt(msg, {
        buttons: {
            Yes: true,
            No: false
        },
        top: 200,
        callback: responseGetForConflict
    })
}

function responseGetForConflict(btn){
    if (btn) {
        new Ajax.Request(_urlBlock, {
            method: 'get'
        });
    }
    else {
        enable_buttons();
        return false;
    }
}

function conflictTimeForAppointment(msg, form, id, cust_name, target_url){
    _formname = form;
    _urlBlock = target_url;
    jQuery.prompt(msg, {
        submit: submitfuncForConflict,
        buttons: {
            Yes: true,
            No: false
        },
        top: 200
    });
}

function submitfuncForConflict(v, m, f){
    if (v) {
        var customer_name = $('cust_info').childNodes[1].innerHTML;
        customer_name = customer_name.substring(0, customer_name.indexOf(','));
        txt = "Do you want to send notification to " + customer_name + "?<select name='notify'><option value='E'>Email</option><option value='T'>Text</option><option value='N'>None</option></select>"
        sendNotification(txt, _urlBlock, _formname);
    }
    else {
        enable_buttons();
		if ($('exist_status'))
		$('appointment_status').value = $('exist_status').value;
    }
}

function responseGet(btn){
    if (btn) {
        $(_formname).action = _urlBlock;
        $(_formname).request();
    }
    else {
        return false;
    }
}

function keypress_handle_dropdown(e, form_element_id){
    var numCharCode = e.keyCode;
    var browser = navigator.appName;
    if (browser == 'Netscape') {
        if (numCharCode == 40 || numCharCode == 38 || numCharCode == 37 || numCharCode == 39) {
            if (document.getElementById('createOption').value == 'block_time_name' && numCharCode != 40 && numCharCode != 39) {
                $('appnt_form').style.display = '';
                $('block_time_form').style.display = 'none';
            }
            else 
                if (document.getElementById('createOption').value == 'customer_id' && numCharCode != 38 && numCharCode != 37) {
                    $('appnt_form').style.display = 'none';
                    $('block_time_form').style.display = '';
                }
        }
    }
}

function resetNewApp(){
    document.getElementById('createOption').value = 'customer_id';
}

function changeBlock(form_element_id){
    if (form_element_id == 'block_time_name') {
        $('appnt_form').style.display = 'none';
        $('block_time_form').style.display = '';
    }
    else {
        $('appnt_form').style.display = '';
        $('block_time_form').style.display = 'none';
    }
    if ($(form_element_id)) 
        $(form_element_id).activate();
}

function hideBlock(form_name){
    $(form_name).style.display = "none";
}

function changeBlockForm(){
    $('override_page').value = 'new'
}

function hideApptForm(form_name, label){
    _form_name = form_name;
    _label = label;
    if (_dirty_bit == true) {
        jQuery.prompt("Are you sure you want to cancel your changes?", {
            buttons: {
                Yes: true,
                No: false
            },
            top: 200,
            callback: hideApptDiv
        });
    }
    else {
        if (($('source') != null) && ($('source').value == 'Custview')) {
            window.location.href = $('cust_list_url').value;
        }
        else {
            $('app_form_div').innerHTML = '';
            $('timepicker').style.visibility = 'hidden';
        }
    }
}

function hideApptDiv(btn){
    if (btn) {
        if (($('source') != null) && ($('source').value == 'Custview')) {
        
            window.location.href = $('cust_list_url').value;
        }
        else 
            if (($('source') != null) && ($('source').value == 'free_appt')) {
                // RETURN TO BUSINESS HOMEPAGE
                window.location.href = $('bus_url').value;
            }
            else {
                unsetDirtyBit();
                $('app_form_div').innerHTML = '';
                $('timepicker').style.visibility = 'hidden';
            }
    }
    else 
        return false;
}

function showResult(btn){
    if (btn) {
        if (document.form_calendar) {
            select_all();
        }
        if ($('form_id')) {
            form_id = $('form_id').value;
            if ($('form_id').value == 'app_form' && $('cust_list_url')) 
                $('cust_list_url').value = _action;
        }
        return false;
    }
    else {
        window.location.href = _link;
    }
}

function unsetDirtyBit(){
    _dirty_bit = 0;
}

function showInError(elementId){
    if ($(elementId)) {
        if (!(Prototype.Browser.IE)) {
            $(elementId).style.display = 'table';
        }
        $(elementId).style.backgroundColor = 'red';
        $(elementId).style.padding = '2px';
    }
    
}

function toggle_calendar(obj, idd, cal_app_mess){
    _obj = obj;
    _idd = idd;
    if (!obj.checked) {
        jQuery.prompt(cal_app_mess, {
            buttons: {
                Yes: false,
                No: true
            },
            callback: toggleCheckbox
        });
    }
}

function toggleCheckbox(btn){
    if (btn) {
        $(_idd).checked = true;
    }
}

function toggle_calendar_edit(obj, idd, cal_app_mess, element_id, div_id){
    _obj = obj;
    _idd = idd;
    _element_id = element_id;
    _div_id = div_id;
    if (!obj.checked) {
        jQuery.prompt(cal_app_mess, {
            buttons: {
                Yes: false,
                No: true
            },
            callback: toggleCheckbox1
        });
    }
    else {
        $(_div_id).style.display = ($(_element_id).checked == true) ? '' : 'none';
    }
}

function toggleCheckbox1(btn){
    if (btn) {
        $(_idd).checked = true;
        
    }
    else {
        $(_div_id).style.display = ($(_element_id).checked == true) ? '' : 'none';
    }
}

function toggle_bio(element_id, div_id){
    $(div_id).style.display = ($(element_id).checked == true) ? '' : 'none';
    
}

function togglecustomerInfo(clear_prev_value){
    obj = $('addnewcustomer');
    if (obj.checked) {
        $('customer_info').style.display = "";
        if (clear_prev_value == 'yes') {
            $('customer_first_name').value = "";
            $('customer_last_name').value = "";
            $('customer_email_address').value = "";
            $('customer_mobile_phone').value = "";
            $('customer_home_phone').value = "";
        }
        $('existing_customer').style.display = 'none';
    }
    else {
        $('existing_customer').style.display = "";
        $('customer_info').style.display = 'none';
    }
}

function isOfferedService(obj){
    if (obj.options[obj.selectedIndex].className == "gray") {
        $('error_msg').innerHTML = "<font color='red'>" + obj.options[obj.selectedIndex].text + " is not offered by selected staff member.Please choose other</font>";
        obj.selectedIndex = 0;
    }
    else {
        $('error_msg').innerHTML = "";
    }
    
}

// for creating block time and appointment
function toggleAppointmentAndBlock(value){
    if (value == "Appointment") {
        $('appt_form').style.display = "";
        $('block_time_form').style.display = 'none';
    }
    else {
        $('appt_form').style.display = 'none';
        $('block_time_form').style.display = "";
    }
}

function deleteBlock(action, token, msg){
    _token = token;
    if (typeof view != 'undefined') {
        _urlBlock = action + "&view=" + view;
    }
    else {
        _urlBlock = action;
    }
    jQuery.prompt(msg, {
        buttons: {
            Yes: true,
            No: false
        },
        top: 200,
        callback: remove_block
    });
}

function remove_block(btn){
    if (btn) {
        new Ajax.Request(_urlBlock, {
            asynchronous: true,
            evalScripts: true,
            parameters: 'authenticity_token=' + encodeURIComponent(_token)
        });
        return false;
    }
}

function deleteConfirm(action, token, msg){
    if ($('staff_view')) 
        view = $('staff_view.value')
    else 
        view = ''
    _token = token;
    _urlBlock = action;
    jQuery.prompt(msg, {
        buttons: {
            Yes: true,
            No: false
        },
        top: 200,
        callback: delete_confirmed
    });
}

function delete_confirmed(btn){
    if (btn) {
        new Ajax.Request(_urlBlock, {
            asynchronous: true,
            evalScripts: true,
            parameters: 'authenticity_token=' + encodeURIComponent(_token)
        });
        toggle_visibility_of_fields('show');
        return false;
    }
}

function cancelConfirm(action){
    _link =  window.location.protocol + "//" + window.location.host + action;
    if (_dirty_bit == true) {
        jQuery.prompt("Are you sure you want to cancel your changes?", {
            buttons: {
                Yes: true,
                No: false
            },
            top: 200,
            callback: processAction
        });
    }
    else {
        window.location.href = _link;
    }
}

function confirmSave(){
    jQuery.prompt('The business name once saved cannot be changed. Are you sure you want to proceed ?', {
        buttons: {
            Yes: true,
            No: false
        },
        callback: submit_form
    });
}

function submit_form(btn){
    if (btn) {
        document.formone.submit();
    }
}

function processAction(btn){
    if (btn) {
        window.location.href = _link;
    }
}

function cancelDestroy(){
    jQuery.prompt('Appointment exist, so you cannot delete. ');
}

function enterAlphabets(){
    jQuery.prompt('Please Enter Alphabets Only ');
}

function setDirtyBit(){
    _dirty_bit = 1;
}

function sDirtyBit(){

    ff_bit = 1;
}

function toggle_theme(){
    if ($('business_biz_theme_id_').checked == true) {
        $('colorplatebox').style.display = "block";
    }
    else {
        $('colorplatebox').style.display = "none";
    }
}

function toggle_payment_fields(){
    if ($('pay_labels').style.display == "block") {
        document.getElementById('pay_labels').style.display = "none";
        document.getElementById('pay_fields').style.display = "block";
		
		document.getElementById('business_cc_type').disabled  = false;
		document.getElementById('business_cc_number').disabled  = false;
		document.getElementById('business_exp_month').disabled  = false;
		document.getElementById('business_exp_year').disabled  = false;
    }
}

function changeSuperStatus(){
    if (_is_super) {
        jQuery.prompt('Are you sure you want to proceed ?', {
            buttons: {
                Yes: true,
                No: false
            },
            callback: submit_form
        });
        return false;
    }
    else {
        document.formone.submit();
        return true;
    }
}

function goToSetUpDone(action){
    _action = action;
    if (_is_super) {
        jQuery.prompt('Are you sure you want to proceed ?', {
            buttons: {
                Yes: true,
                No: false
            },
            callback: setUpDone
        });
        return false;
    }
    else {
        window.location.href = _action;
        return true;
    }
}

function setUpDone(){
    window.location.href = _action;
}

function DecreaseStaffCount(count, id){
    if ($(id)) {
        $(id).innerHTML = count;
    }
    
    
}

function changeSuperStatus1(){
    if (_is_super) {
        jQuery.prompt('Are you sure you want to delete ?', {
            buttons: {
                Yes: true,
                No: false
            },
            callback: submit_form
        });
        return false;
    }
    else {
        document.formone.submit();
        return true;
    }
}

function setSuper(a){
    if (a == 'S') 
        _is_super = 1;
}

/*Depending on the workday enable/disable the work hour*/
function checkWorkDay(el, day, form){
    if (el == 'N') {
        $("calendar_" + day + "_start_time1").disabled = true;
        $("calendar_" + day + "_end_time1").disabled = true;
        $("calendar_" + day + "_start_time2").disabled = true;
        $("calendar_" + day + "_end_time2").disabled = true;
        $("calendar_" + day + "_start_time1").value = "";
        $("calendar_" + day + "_end_time1").value = "";
        $("calendar_" + day + "_start_time2").value = "";
        $("calendar_" + day + "_end_time2").value = "";
        /*        $(day + "_time1").style.display = 'none';
         $(day + "_time2").style.display = 'none';
         $(day + "_time3").style.display = 'none';
         $(day + "_time4").style.display = 'none';
         closeTimePickerForWork(form);*/
    }
    else 
        if (el == 'Y') {
            $("calendar_" + day + "_start_time1").disabled = false;
            $("calendar_" + day + "_end_time1").disabled = false;
            $("calendar_" + day + "_start_time2").disabled = false;
            $("calendar_" + day + "_end_time2").disabled = false;
        /*$(day + "_time1").style.display = '';
         $(day + "_time2").style.display = '';
         $(day + "_time3").style.display = '';
         $(day + "_time4").style.display = '';   */
        }
}

/*associate services to the calendar*/
function addId(allservices, calendarservices){
    for (i = allservices.length - 1; i >= 0; i--) {
        if (allservices.options[i].selected) {
            if (allservices.options[i].value != "" && allservices.options[i].value.length > 0) {
                calendarservices[calendarservices.length] = new Option(allservices.options[i].text, allservices.options[i].value);
                allservices.options[i] = null;
            }
            
        }
    }
}

/*Select the service associated with the calendar before save*/
function select_all(){
    select_box = $('calendar_service_id');
    if ((select_box.options.length == 0) && ($('calendar_any_service').checked == false)) {
        jQuery.prompt('Please configure a service for this calendar');
        return false;
    }
    else {        
//        if (($('calendar_mon_work_day').selectedIndex == 1) &&
//        ($('calendar_tue_work_day').selectedIndex == 1) &&
//        ($('calendar_wed_work_day').selectedIndex == 1) &&
//        ($('calendar_thu_work_day').selectedIndex == 1) &&
//        ($('calendar_fri_work_day').selectedIndex == 1) &&
//        ($('calendar_sat_work_day').selectedIndex == 1) &&
//        ($('calendar_sun_work_day').selectedIndex == 1)) {
//			alert("in else if")
//            jQuery.prompt('Please configure the calendar if you add services');
//            return false;
//        }
//        else {
            for (i = 0; i < select_box.options.length; i++) {
                select_box.options[i].selected = true;
            }
            disable_calendar_buttons();
            document.form_calendar.submit();
            return true;
//        }
    }
}

function disable_calendar_buttons(){
    save_btn = document.getElementsByName('cancel');
    for (i = 0; i < save_btn.length; i++) {
        save_btn[i].disabled = true;
        save_btn[i].style.color = "#999999";
    }
}

/*Remove the service associated with calendar*/
function removeSelected(calendarServicesList, allServicesList){
    for (i = calendarServicesList.length - 1; i >= 0; i--) {
        if (calendarServicesList.options[i].selected) {
            /*check if that service doesnot exist in the all service then move it to All services List*/
            allServicesList[allServicesList.length] = new Option(calendarServicesList.options[i].text, calendarServicesList.options[i].value);
            calendarServicesList.options[i] = null;
        }
    }
}

/*  Function to alert staff if mobile no. has not been setup */
function check_if_mobile_phone_configured(mobile_phone){
    if (($('calendar_new_customer_notify_method').value == 'B' || $('calendar_new_customer_notify_method').value == 'T' ||
    $('calendar_request_notify_method').value == 'B' ||
    $('calendar_request_notify_method').value == 'T' ||
    $('calendar_appointment_notify_method').value == 'B' ||
    $('calendar_appointment_notify_method').value == 'T' ||
    $('calendar_move_notify_method').value == 'B' ||
    $('calendar_move_notify_method').value == 'T' ||
    $('calendar_cancel_notify_method').value == 'B' ||
    $('calendar_cancel_notify_method').value == 'T' ||
    $('calendar_remind_staff_method').value == 'B' ||
    $('calendar_remind_staff_method').value == 'T' ||
    $('calendar_contact_us_notify_method').value == 'B' ||
    $('calendar_contact_us_notify_method').value == 'T')  &&
    mobile_phone == '') {
        jQuery.prompt('<div align="center">WARNING</div> You have set staff notification preferences to include Text messages, ' +
        'but have not setup a valid mobile phone for this staff member.', {
            buttons: {
                Close: false
            },
            callback: select_all
        });
        if (navigator.appName == "Microsoft Internet Explorer") {
            window.document.execCommand('Stop');
        }
        else {
            window.stop();
        }
    }
    else {
        select_all();
    }
}

/*Enable/Disable the services selected on the basis of 'All Service' field*/
function toggle_service(element_id, div_id){
    $(div_id).style.display = ($(element_id).checked == true) ? "none" : "block";
}

function toggle_testimonies(element_id, div_id){
    $(div_id).style.display = ($(element_id).checked == true) ? '' : 'none';
}

/* Making a request.*/
function createRequestObject(){
    /* Initialising the variable xmlhttp */
    var xmlhttp = false;
    /* Try and catch block for creating xmlhttp object according to the browser */
    try {
        /* The xmlhttp object is built into the Microsoft XML Parser. */
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch (e) {
        try {
            /* The xmlhttp object is built into the Microsoft IE. */
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (E) {
            xmlhttp = false;
        }
    }
    /* The xmlhttp object is built into the browsers other than Microsoft IE. */
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}

function send_messages(){
    checkbox_elements = document.getElementsByName('appointment');
    var ids = "";
    for (var i = 0; i < checkbox_elements.length; i++) {
        if ($('select_all').checked == true) {
            ids = ids + checkbox_elements[i].value + ',';
        }
        else 
            if (checkbox_eslements[i].checked == true) {
                ids = ids + checkbox_elements[i].value + ',';
            }
    }
}

function applyTimeToAll(){
    var k = -1;
    var r = 0;
    var n = 0;
    var weekDays = new Array("sun", "mon", "tue", "wed", "thu", "fri", "sat");
    for (i = 0; i < weekDays.length; i++) {
        if (weekDays[i] == _selected_day && $('calendar_' + weekDays[i] + '_work_day').value == 'Y') {
            k = i;
            break;
        }
    }
    for (i = 0; i < weekDays.length; i++) {
        if ($('calendar_' + weekDays[i] + '_work_day').value == 'Y') {
            n = i;
            break;
        }
    }
    if (n < k) {
        // condition when for eg. sun is made yes an no time
        // filled and mon is made yes with time filled, them sun blank time is picked
        copytime(n, weekDays)
    }
    else {
        if (k != -1) {
            // condition when the last day selected yes is filled with time 
            // and needs to be copied to other fields below it
            copytime(k, weekDays)
        }
        else {
            for (i = 0; i < weekDays.length; i++) {
                if ($('calendar_' + weekDays[i] + '_work_day').value == 'Y') {
                    r = i;
                    break;
                }
            }
            copytime(r, weekDays)
            
        }//end of else
    }
}

function copytime(r, weekDays){
    var choosenDay = weekDays[r];
    for (l = r; l < weekDays.length; l++) {
        var applydays = weekDays[l];
        if ($('calendar_' + applydays + '_work_day').value == 'Y') {
            $('calendar_' + applydays + '_start_time1').value = $('calendar_' + choosenDay + '_start_time1').value;
            $('calendar_' + applydays + '_end_time1').value = $('calendar_' + choosenDay + '_end_time1').value;
            $('calendar_' + applydays + '_start_time2').value = $('calendar_' + choosenDay + '_start_time2').value;
            $('calendar_' + applydays + '_end_time2').value = $('calendar_' + choosenDay + '_end_time2').value;
        }
    }
}

function doSubmit(e){
    var browserName = navigator.appName;
    if (browserName == "Microsoft Internet Explorer") {
        if (window.event) 
            if (e.keyCode) 
                var numCharCode = e.keyCode;
    }
    else {
        var numCharCode = (window.Event) ? e.which : e.keyCode;
    }
    if (numCharCode == 13) {
        document.forms[0].submit();
    }
}

function sigin_from_popup(e){
    var browserName = navigator.appName;
    if (browserName == "Microsoft Internet Explorer") {
        if (window.event) 
            if (e.keyCode) 
                var numCharCode = e.keyCode;
    }
    else {
        var numCharCode = (window.Event) ? e.which : e.keyCode;
    }
    if (numCharCode == 13) {
        $('popup_signin').request({
        
            onCreate: function(){
                $('pop_up_ajax_apinner').style.display = '';
            },
            onComplete: function(){
                $('pop_up_ajax_apinner').style.display = 'none';
            }
        });
    }
}

function sigin_from_popup(e){
    var browserName = navigator.appName;
    if (browserName == "Microsoft Internet Explorer") {
        if (window.event) 
            if (e.keyCode) 
                var numCharCode = e.keyCode;
    }
    else {
        var numCharCode = (window.Event) ? e.which : e.keyCode;
    }
    if (numCharCode == 13) {
        $('popup_signin').request();
    }
}

function doSubmit1(e){
    var browserName = navigator.appName;
    if (browserName == "Microsoft Internet Explorer") {
        if (window.event) 
            if (e.keyCode) 
                var numCharCode = e.keyCode;
    }
    else {
        var numCharCode = (window.Event) ? e.which : e.keyCode;
    }
    if (numCharCode == 13) 
        search_customers();
}

function display_preview(iframe_document_content){
    RedBox.showOverlay();
    RedBox.addHiddenContentPreview(iframe_document_content);
}

function about(container_id, show, hide){
    Element.toggle(container_id)
    Element.toggle(show);
    Element.toggle(hide);
}

//  Function to suggest whether password matches confirmation
function checkPassword(entered_password, password_confirmation, update_element){
    var pass = $(entered_password).value;
    var repass = $(password_confirmation).value;
    if (repass.length != 0) 
        if (pass.length != repass.length) {
            $(update_element).style.display = 'block';
            $(update_element).innerHTML = '<span style="color:red; font-size:88%;">Password and Re-type Password do not match</span>';
        }
        else {
            var flag = 1;
            for (i = 0; i < repass.length; i++) {
                if (pass.charAt(i) != repass.charAt(i)) {
                    flag = 0;
                    break;
                }
                else {
                    flag = 1;
                }
            }
            if (flag == 1) {
                $(update_element).style.display = 'block';
                $(update_element).innerHTML = '<span style="color:green; font-size:88%;">Password is matched</span>';
            }
            
        }
    else 
        $(update_element).innerHTML = '';
}

function checkMinisite(){
    if ($('business_mini_site_name').value == '') {
        $('suggest').innerHTML = '';
        return false;
    }
    else {
        return true;
    }
}

function checkOpenTimingsContentForWordLimit(param){
    if ($('business_mini_site_services_page')) 
    $('business_open_timings').value = $('line1').value + '\n' + $('line2').value + '\n' + $('line3').value + '\n' + $('line4').value + '\n' + $('line5').value + '\n' + $('line6').value + '\n' + $('line7').value + '\n' + $('line8').value
    var flag = false;
    var open_time_one = $('business_open_timings').value;
    var open_time = trim(open_time_one);
    $('business_open_timings').value = open_time;
    var open_time_values = open_time.split('\n');
    var len = open_time_values.length;
    for (var i = 0; i < len; i++) {
        var name = navigator.appName;
        if (name == "Microsoft Internet Explorer") {
            if (open_time_values[i].length > 26) {
                jQuery.prompt('Please limit the Open Times information to 8 lines and 25 characters per line');
                return false;
            }
            else {
                flag = true;
            }
        }
        else {
            if (open_time_values[i].length > 25) {
                jQuery.prompt('Please limit the Open Times information to 8 lines and 25 characters per line');
                return false;
            }
            else {
                flag = true;
            }
        }
    }

	if (flag == true) {
        if (param == "save") {
            document.formone.submit();
            return true;
        }
        else {
            previewMiniWebSite();
        }
    }
}

function trim(str){
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function checkFormFieldValuesForCreateAppointment(){
    var error_msg = "";
    var flag = true;
    
    if (($('appointment_start_time').value == "") || ($('appointment_start_time').value.length == 0)) {
        $('appointment_start_time').style.border = 'solid 1px red';
        error_msg = error_msg + "Start time is required";
        flag = false;
    }
    
    if (($('appointment_end_time').value == "") || ($('appointment_end_time').value.length == 0)) {
        $('appointment_end_time').style.border = 'solid 1px red';
        error_msg = error_msg + "\n End time is required"
        flag = false;
    }
    
    if (($('appointment_start_time').value != "") && ($('appointment_end_time').value != "") && $('appointment_end_time').value < $('appointment_start_time').value) {
        error_msg = error_msg + '\n End time should be greater than Start time';
        $('appointment_start_time').style.border = 'solid 1px red';
        $('appointment_end_time').style.border = 'solid 1px red';
        flag = false;
    }
    if (flag) {
        return true;
    }
    else {
        $('errors').innerHTML = error_msg;
        return false;
    }
    
}

/* for create appt service change and fill end time funct*/
function getServicesForStaff(staff_select_id, service_select_id){
    var staff = $(staff_select_id).value;
    var service_box = $(service_select_id);
    var str = [];
    if (staff != '') {
        str = staff_arr[staff];
    }
    selected_services = str.join(',');
    str_arry = selected_services.split(",");
    if (selected_services == '' || selected_services.length == 0) {
        var serv = "";
        var ele = "";
        for (i = 0; i < service_arr.length; i++) {
            serv = service_arr[i];
            ele = ele + service_arr[i][0] + ",";
        }
        
        selected_services = ele.substring(0, ele.length - 1);
    }
    for (j = 0; j < service_box.length; j++) {
        // if (selected_services.match(service_box.options[j].value) == service_box.options[j].value) {
        if (str_arry.indexOf(service_box.options[j].value) != -1 || service_box.options[j].value == '' || str_arry[0] == '') {
            service_box.options[j].style.color = "black";
        }
        else {
            service_box.options[j].style.color = "gray";
        }
    }
    
}

/* for create appt service change and fill end time funct*/
function getServicesForCalendar(cal_select_id, service_select_id){

    var str = "";
    var cal = $(cal_select_id).value;
    var service_box = document.getElementById(service_select_id);
    var str = [];
    if (cal != '') {
        str = cal_arr[cal];
    }
    selected_services = str.join(',');
    str_arry = selected_services.split(",");
    if (selected_services == '' || selected_services.length == 0) {
        var serv = "";
        var ele = "";
        for (i = 0; i < service_arr.length; i++) {
            serv = service_arr[i];
            ele = ele + service_arr[i][0] + ",";
        }
        
        selected_services = ele.substring(0, ele.length - 1);
    }
    for (j = 0; j < service_box.length; j++) {
        if (str_arry.indexOf(service_box.options[j].value) != -1 || service_box.options[j].value == '' || str_arry[0] == '') {
            service_box.options[j].style.color = "black";
        }
        else {
            service_box.options[j].style.color = "gray";
        }
    }
    
}

/* for create appt service change and fill end time funct*/
function getServicesForCalendarOnLoad(cal_select_id_value, service_select_id){
    var str = "";
    var cal = cal_select_id_value;
    var service_box = document.getElementById(service_select_id);
    var str = [];
    if (cal != '') {
        str = cal_arr[cal];
    }
    selected_services = str.join(',');
    str_arry = selected_services.split(",");
    if (selected_services == '' || selected_services.length == 0) {
        var serv = "";
        var ele = "";
        for (i = 0; i < service_arr.length; i++) {
            serv = service_arr[i];
            ele = ele + service_arr[i][0] + ",";
        }
        
        selected_services = ele.substring(0, ele.length - 1);
    }
    for (j = 0; j < service_box.length; j++) {
        if (str_arry.indexOf(service_box.options[j].value) != -1 || service_box.options[j].value == '' || str_arry[0] == '') {
            service_box.options[j].style.color = "black";
        }
        else {
            service_box.options[j].style.color = "gray";
        }
    }
    
}

function validateService(staff_select_id, service_select_id, view){
    //	alert("I m in")
    //	alert(staff_select_id)
    //	alert(service_select_id)
    //	alert(view)
    if ($(staff_select_id).value != '') {
        var view = view;
        var service_id = $(service_select_id).value;
        var staff = $(staff_select_id).value;
        var str = staff_arr[staff];
        selected_services = str.join(',');
        if (selected_services.length == 0) {
            var serv = "";
            var ele = "";
            for (i = 0; i < service_arr.length; i++) {
                serv = service_arr[i];
                ele = ele + service_arr[i][0] + ",";
            }
            selected_services = ele.substring(0, ele.length - 1);
        }
        if (!selected_services.match(service_id)) {
            jQuery.prompt('Staff selected does not provide the particular service. Please select a different service or a different staff member that does provide the service.', {
                buttons: {
                    Ok: true
                },
                top: 200,
                callback: resetservice(service_select_id, view)
            });
        }
    }
}

function validateServiceforCal(cal_select_id, service_select_id, view){
    if ($(cal_select_id).value != '') {
        var view = view;
        var service_id = $(service_select_id).value;
        var cal = $(cal_select_id).value;
        var str = cal_arr[cal];
        selected_services = str.join(',');
        if (selected_services.length == 0) {
            var serv = "";
            var ele = "";
            for (i = 0; i < service_arr.length; i++) {
                serv = service_arr[i];
                ele = ele + service_arr[i][0] + ",";
            }
            selected_services = ele.substring(0, ele.length - 1);
        }
        if (!selected_services.match(service_id)) {
            jQuery.prompt('Staff selected does not provide the particular service. Please select a different service or a different staff member that does provide the service.', {
                buttons: {
                    Ok: true
                },
                top: 200,
                callback: resetservice(service_select_id, view)
            });
        }
    }
}

function populateEndTime(ele){
    var start_time = $('appointment_start_time').value;
    if (start_time != '') {
        time = get_end_time(start_time, ele);
    }
    else {
        time = start_time;
    }
    
    $('appointment_end_time').value = time;
    $('end_time').innerHTML = time;
}

function populateEndTimechange(ele){
    var start_time = $('appointment_start_time').value == "" ? $('existing_start_time').innerHTML : $('appointment_start_time').value;
    start_time = start_time.replace(/(^\s*)|(\s*$)/g, '').toLowerCase();
    time = get_end_time(start_time, ele);
    $('appointment_start_time').value = start_time;
    $('appointment_end_time').value = time;
    $('end_time').innerHTML = time;
}

function resetTime(view){
    if (view == "Custview" && $('service') && $('service').value == '') {
        $('appointment_start_time').value = "";
        $('appointment_end_time').value = "";
        if ($('end_time').innerHTML != "") 
            $('end_time').innerHTML = "";
    }
}

function get_end_time(start_time, duration){
    var hour = start_time.substring(0, start_time.indexOf(":"));
    hour_arr = hour.match(/\d/g);
    if (hour_arr[0] == '0') {
        hour = parseInt(hour_arr[1]);
    }
    else {
        hour = parseInt(hour_arr.join(''));
    }
    hour = (hour + 12) % 12;
    var min = parseInt(start_time.substring(start_time.indexOf(":") + 1, start_time.length - 2));
    var time_clk = start_time.substring(start_time.length - 2, start_time.length);
    hour = hour + ((time_clk == 'PM' || time_clk == 'pm') ? 12 : 0);
    var start_date = new Date(2009, 11, 05, hour, min);
    var end_date = new Date();
    end_date.setTime(start_date.getTime() + parseInt(duration * 60 * 1000));
    var time_in_string = '';
    var hours, h;
    h = end_date.getHours();
    hours = ((h + 11) % 12) + 1;
    time_in_string = ((hours < 10) ? "0" : "") + hours;
    time_in_string = time_in_string + ":" + (((end_date.getMinutes() < 10) ? "0" : "")) + end_date.getMinutes();
    time_in_string = time_in_string + " " + ((h < 12) ? "AM" : "PM")
    return time_in_string;
}

function reset_fields(staff_select_id, service_select_id){
    $(staff_select_id).selectedIndex = "";
    $(service_select_id).selectedIndex = "";
}

function resetservice(service_select_id, view){
    if (view == 'business') {
        $(service_select_id).selectedIndex = "";
    }
    else 
        if (view == 'miniwebsite') {
            $('appointment_calendar_id').value = "";
        }
}

function checkDateFormat(cus_dob_value){
    if ($('dob')) {
		if ($('dob').value == ''  && (cus_dob_value == 'O' || cus_dob_value == 'N'))
            document.formone.submit();
        else{		
            validate_dob(); 
        }
    }
    else {
        document.formone.submit();
    }    
}

function check_if_dob_entered()
{    
     if ($('dob').value == ''  )        
        document.formone.submit(); 
    else
        validate_dob(); 
}

function validate_dob()
{
    var dateOfBirth = $('dob').value;
    msg = isDate(dateOfBirth, 4);
    if ($('dob') && msg != true && dateOfBirth != 'mm/dd/yyyy') {
        
        jQuery.prompt(msg, {
            buttons: {
                Ok: true
            },
            top: 200
        });
    }
    else {
        if (dateOfBirth == 'mm/dd/yyyy') {
            $('dob').value = "";
        }
        document.formone.submit();
    }
}

function showServiceDesc(){
    var service_id = $('appointment_service_id').value;
    var desc = "";
    for (i = 0; i < service_arr.length; i++) {
        if (service_id == service_arr[i][0]) {
            desc += service_arr[i][1];
            desc += "<br>Duration : " + service_arr[i][2] + " minutes";
            desc += "<br>Price : " + service_arr[i][3];
            break;
        }
    }
    //	alert("WAFDSAFSD")
    $('serv_desc').innerHTML = escape_html_string(desc);
    
}

// Function to replace '+' by ' ' globally
function escape_html_string(string){
    var new_str = string.replace(/\+/g, ' ');
    return unescape(new_str);
}

/* This function goes through the options for the given
 drop down box and removes them in preparation for
 a new set of values    */
function emptyList(box){
    // Set each option to null thus removing it
    while (box.options.length) 
        box.options[0] = null;
}

/* This function assigns new drop down options to the given
 drop down box from the list of lists specified   */
function fillList(box, service_id, action, id_cal, mode, label_staff, from_staff){
    flag = false;
    if (from_staff != '') {
        first_staff = from_staff;
        if (service_id != "") {
            for (k = 0; k < staff_arr.length; k++) {
                if (staff_arr[k][1].length == 0 && staff_arr[k][0] == from_staff) {
                    flag = true;
                }
            }
            //cal-service-arr holds name of staff and service provided by him
            var calendars_of_service = service_cal_arr[service_id];
            if (calendars_of_service != '') {
                for (j = 0; j < calendars_of_service.length; j++) {
                    staff_calendar_id = calendars_of_service[j];
                    if (staff_calendar_id == from_staff) 
                        flag = true;
                }
            }
        }
        if (flag) {
            option = new Option(staff_name_arr[first_staff][0], first_staff);
            box.options[box.length] = option;
        }
        else 
            from_staff = '';
    }
    else 
        from_staff = '';
    
    if (mode == "change_appointment") 
        str = "Change " + label_staff;
    else 
        str = "Select " + label_staff;
    option = new Option(str, str);
    box.options[box.length] = option;
    
    if (service_id != "") {
        //cal-service-arr holds name of staff and service provided by him
        var calendars_of_service = service_cal_arr[service_id];
        for (j = 0; j < calendars_of_service.length; j++) {
            staff_calendar_id = calendars_of_service[j];
            // Create a new drop down option with the
            // display text and value from arr
            if (!staff_name_arr[staff_calendar_id]) {
                continue;
            }
            if (from_staff != staff_calendar_id) {
                option = new Option(staff_name_arr[staff_calendar_id][0], staff_calendar_id);
                // Add to the end of the existing options
                box.options[box.length] = option;
            }
        }
        for (k = 0; k < staff_arr.length; k++) {
            if (staff_arr[k][1].length == 0) {
                calId = staff_arr[k][0];
                if (from_staff != calId) {
                    option = new Option(staff_name_arr[calId][0], calId);
                    box.options[box.length] = option;
                }
            }
        }
        if (box.length > 1) {
            option = new Option("No Preference", "");
            box.options[box.length] = option;
        }
    }
    else {//if change service is seelcted, all calendars should be displayed including change staff and no pref
        for (k = 0; k < staff_arr.length; k++) {
            calId = staff_arr[k][0];
            if (from_staff != calId) {
                option = new Option(staff_name_arr[calId][0], calId);
                box.options[box.length] = option;
            }
            box.value = "";
        }
        if (box.length > 1) {
            option = new Option("No Preference", "");
            box.options[box.length] = option;
        }
    }
    
    if (action == 'load') 
        box.value = id_cal;
    else {
        if (from_staff != '') {
            box.value = from_staff;
        }
        else {
            box.value = str;
            //added for setting all services to black when "select service" is selected
            var service_box = document.getElementById("appointment_service_id");
            for (j = 0; j < service_box.length; j++) {
                service_box.options[j].style.color = "black";
            }
        }
        
        
        $('customer_left_form').request({
            onCreate: function(){
                $('ajax_apinner').style.display = '';
            },
            onComplete: function(){
                $('ajax_apinner').style.display = 'none';
            }
        });
    }
	
    if (box.length == 3) {
        for (k = 2; k >= 0; k--) {
            if (box.options[k].value == str || box.options[k].value == '') {
                box.options[k] = null;
                
            }
        }
        
        $('customer_left_form').request({
            onCreate: function(){
                $('ajax_apinner').style.display = '';
            },
            onComplete: function(){
                $('ajax_apinner').style.display = 'none';
            }
        });
    }
    if (typeof staff_name_arr[box.value] != 'undefined'){
      $("staff_desc").innerHTML = escape_html_string(staff_name_arr[box.value][1]);
    }
    
}

/* This function performs a drop down list option change by first
 emptying the existing option list and then assigning a new set   */
function changeList(action, mode, label_staff, from_staff){
    // Isolate the appropriate list by using the value
    // of the currently selected option
    var service_box = $('appointment_service_id');
    var staff_box = $('appointment_calendar_id');
    var service_id = service_box.value;
    var id_cal = staff_box.value;
    
    if (from_staff == '') {
        if ($('appointment_calendar_id').value != '') 
            from_staff1 = $('appointment_calendar_id').value
        else 
            from_staff1 = ''
    }
    else 
        from_staff1 = from_staff
    
    // Next empty the staff list
    emptyList(staff_box);
    // Then assign the new list values
    
    fillList(staff_box, service_id, action, id_cal, mode, label_staff, from_staff1);
}

function displayErrorMessage(msg){
    jQuery.prompt(msg, {
        buttons: {
            Ok: true
        },
        top: 200
    
    });
}

function getStaffMember(selected_service_id, all_staff, from){
    var selected_service_id = $(selected_service_id).value;
    var all_staff_array = $(all_staff);
    var staff_index = '';
    var staff = '';
    if (from == 'change_app') 
        new_arr = cal_arr;
    else 
        new_arr = staff_arr;
    for (i = 0; i < new_arr.length; i++) {
        var str = new_arr[i];
        if (str != null) {
            staff_index = i;
            selected_services = str.join(',');
            if (selected_services.length == 0) {
                var serv = "";
                var ele = "";
                for (j = 0; j < service_arr.length; j++) {
                    serv = service_arr[j];
                    ele = ele + service_arr[j][0] + ",";
                }
                selected_services = ele.substring(0, ele.length - 1);
            }
            if (selected_services.match(selected_service_id)) {
                staff = staff + staff_index + ",";
            }
        }
    }
    staff = staff.substring(0, staff.length - 1);
    for (j = 0; j < all_staff_array.length; j++) {
        if (staff.match(all_staff_array.options[j].value) == all_staff_array.options[j].value) {
            all_staff_array.options[j].style.color = "black"
        }
        else {
            all_staff_array.options[j].style.color = "gray"
        }
    }
}

function mysubmitfunc(v, m, f){
    an = m.children('#notify');
    if (true) {
        window.document.getElementById('notify_method').value = f.notify;
        window.document.getElementById('notify_method_required').value = v;
        return true;
    }
    else {
        window.document.getElementById('notify_method').value = f.notify;
        return false;
    }
}

function sendNotification(msg, url, form){
    _urlBlock = url;
    _formname = form;
    $(_formname).action = url;
    $(_formname).request();
    //    jQuery.prompt(msg, {
    //        submit: mysubmitfunc,
    //        buttons: {
    //            Yes: true,
    //            No: false
    //        },
    //        top: 200,
    //        callback: responseGet
    //    })
}
function checkDirtyBitRecur(action, source,url, view,form,event_type,x,y){
    if (_dirty_bit == 1) {
//		alert("_dirty_bit-->"+_dirty_bit)
		recur_change_option_pop_up(url, view,form,event_type,x,y);
    }
    else {
        disable_buttons();
        if (source == 'Custview' && action != "") {
            if (navigator.appName == "Microsoft Internet Explorer") {
                window.document.execCommand('Stop');
            }
            else {
                window.stop();
            }
            window.location.href = action;
            return false;
        }
        else 
            if (source == 'Calview') {
                //RedBox.close();
                toggle_visibility_and_close();
                return false;
            }
        
    }
	return false;
}

function recur_change_option_pop_up(url, view,form,event_type,x,y){
//	alert("event_type-->"+event_type);
    _urlBlock = url;
//	alert("_urlBlock-->"+_urlBlock)
    _formname = form;
	var txt_block = "This block time is part of a recurring series.  It is block time "+x+" of "+y+".  How do you want to apply this change? <br> ";
	 txt_block += "<input type='radio' name='recur_block_option' value='all' checked='checked' > Apply this change to all block times in the series  <br>";
//	 txt_block += "<input type='radio' name='recur_block_option' value='only'> Apply this change to just this block time  <br>";
	 txt_block += " <input type='radio' name='recur_block_option' value='cancel'> Cancel this change  <br>";
	
	var txt_appt = "This appointment is part of a recurring series.  It is appointment "+x+" of "+y+".  How do you want to apply this change? <br> ";
	 txt_appt += "<input type='radio' name='recur_block_option' value='all' checked='checked' > Apply this change to all appointments in the series  <br>";
//	 txt_appt += "<input type='radio' name='recur_block_option' value='only'> Apply this change to just this appointment  <br>";
	 txt_appt += " <input type='radio' name='recur_block_option' value='cancel'> Cancel this change  <br>";
	
	jQuery.prompt((event_type=='appointment'?txt_appt:txt_block),{
	      callback: callbackrecur
		  });
	return false;
}

function callbackrecur(v,m,f){
	if(f){
		if(f.recur_block_option=="cancel"){
			return false;
		}else{
                 var str = _urlBlock.indexOf('?') != -1 ?  '&' : '?';
			_urlBlock = _urlBlock + str +"recur_option="+f.recur_block_option;
		    $(_formname).action = _urlBlock;
		    $(_formname).request();
		}
	}else
		return false;
		
	
}

function responseGet(btn){
    var url = _urlBlock;
    $(_formname).action = url;
    $(_formname).request();
}

function fill_end_time(t){
    s_id = $('appointment_service_id').value == "" ? $('service').value : $('appointment_service_id').value;
    //if (t != "Custview") {
    for (i = 0; i < service_arr.length; i++) {
        var each_service = new Array();
        each_service = service_arr[i];
        for (k = 0; k < each_service.length; k++) {
            service_id = each_service[0];
            if (each_service[0] == s_id) {
                populateEndTimechange(each_service[2]);
                break;
            }
        }
    }
    //}
}

function appointmentandblockValidation(){
    jQuery.prompt('Please Choose Valid Date and Time.');
}

function changeAppointmentParametes(service_id, staff_calendar_id, appointment_id){
    $('appointment_service_id').value = service_id;
    $('appointment_calendar_id').value = staff_calendar_id;
    $('selected_appointment_id').value = appointment_id;
}

function changeAppointmentParametes(service_id, staff_calendar_id, appointment_id){
    $('appointment_service_id').value = service_id
    $('appointment_calendar_id').value = staff_calendar_id
    $('selected_appointment_id').value = appointment_id
}

function openAppoitmentForm(target_url){
	Balloon.prototype.hideTooltip;
    new Ajax.Updater('red_app_form', target_url, {
        asynchronous: true,
        evalScripts: true,
        onComplete: function(request){
            toggle_visibility_of_fields('hide');
            RedBox.addHiddenContent('red_app_form');
        },
        onLoading: function(request){
            RedBox.loading();
        },
        parameters: 'authenticity_token=' + encodeURIComponent(form_token)
    });
    return false;
}

function showOfferInfo(target_url, type){
    new Ajax.Updater(type, target_url, {
        asynchronous: true,
        evalScripts: true,
        parameters: 'authenticity_token=' + encodeURIComponent(form_token)
    });
    return false;
}

function clearDetails(){
    if ($('wait_detail').style.display == "") 
        $('wait_detail').style.display = 'none';
}

function selectAppointment(){
    jQuery.prompt('Please Select any appointment. ');
}

function enterName(){
    jQuery.prompt('Please Enter Customer name to be searched. ');
}

function selectcustomer(){
    jQuery.prompt('Please Select any Customer. ');
}

function converttime(time){
    var hour = time.substring(0, time.indexOf(":"));
    var min = time.substring(time.indexOf(":") + 1, time.length);
    hour = parseInt(hour, 10);
    if (hour >= 12) {
        hr = hour % 12 == 0 ? 12 : hour % 12;
        start_time = hr + ":" + min;
    }
    else {
        start_time = hour + ":" + min;
    }
    return start_time;
}

function getPosition(id){
    element = $(id);
    var left = 0;
    var top = 0;
    //Loop while this element has a parent.
    while (element.offsetParent) {
        //Sum the current offsets with the total.
        left += element.offsetLeft;
        top += element.offsetTop;
        //Switch position to this element's parent.
        element = element.offsetParent;
    }
    //Do a final increment in case there was no parent or if //the last parent has an offset.
    left += element.offsetLeft;
    top += element.offsetTop;
    //Return the values as x,y.
    return {
        x: left,
        y: top
    };
}

function removeElement(parent, div){
    var d2 = document.getElementById(div);
    ////WriteFile(" removeElement App/Block div : " + div);
    if (d2 != null) {
        d2.parentNode.removeChild(d2);
    }
}

function unique(arrayName){
    var newArray = new Array();
    label: for (var i = 0; i < arrayName.length; i++) {
        for (var j = 0; j < newArray.length; j++) {
            if (newArray[j] == arrayName[i]) 
                continue label;
        }
        newArray[newArray.length] = arrayName[i];
    }
    return newArray;
}

function string_from_date(event_time){
    var time_str = '';
    if (event_time.getHours() < 10) {
        time_str = "0";
    }
    time_str += event_time.getHours() + ":";
    if (event_time.getMinutes() < 10) {
        time_str += "0";
    }
    time_str += event_time.getMinutes();
    return time_str;
}

function date_to_string(event_date){
    var newdatestart = event_date.getFullYear();
    month = event_date.getMonth() + 1;
    day = event_date.getDate();
    if (month <= 9) {
        newdatestart += '-0' + month;
    }
    else {
        newdatestart += '-' + month;
    }
    if (day <= 9) {
        newdatestart += '-0' + day;
    }
    else {
        newdatestart += '-' + day;
    }
    return newdatestart;
}

function replace_override(work_day, start_time1, end_time1, start_time2, end_time2, date_from, date_to){
    from_date_obj = new Date(date_from);
    to_date_obj = new Date(date_to);
    while (from_date_obj <= to_date_obj) {
        var con_div_id = 'con_' + staff_id + '_' + date_to_string(from_date_obj);
        if ($(con_div_id)) {
            reset_all_divs(con_div_id);
            call_new_div(work_day, start_time1, end_time1, start_time2, end_time2, date_to_string(from_date_obj));
        }
        from_date_obj = new Date(from_date_obj.getTime() + 86400000);
    }
}

function replace_override_for_day(work_day, start_time1, end_time1, start_time2, end_time2, staff_id, date_from, date_to){
    from_date_obj = new Date(date_from);
    to_date_obj = new Date(date_to);
    var con_div_id = 'con_' + staff_id + '_' + date_to_string(from_date_obj);
    if ($(con_div_id)) {
        reset_all_divs(con_div_id);
        call_new_div(work_day, start_time1, end_time1, start_time2, end_time2, staff_id);
    }
}

function reset_all_divs(parent_container){
    //	alert("resetting all divs of"+parent_container);
    if ($(parent_container)) {
        //		alert("in if of restet dvi")
        inactive_divs = $(parent_container).getElementsByTagName('div');
        for (i = 0; i < inactive_divs.length - 1; i++) {
            inactive_divs[i].removeClassName('inactive');
        }
    }
    
}

function new_div(start, end, event_day){
    var con_div_id = 'eventLayer_' + staff_id + '_' + event_day;
    var event_start_time = parseDate(start);
    var event_end_time = parseDate(end);
    while (event_start_time < event_end_time) {
        div_id = "div_" + event_day + "_" + string_from_date(event_start_time);
        $(div_id).removeClassName('pastweek');
        $(div_id).addClassName('inactive');
        event_start_time = new Date(event_start_time.getTime() + (_time_duration_unit * 60000));
    }
    if (string_from_date(event_start_time) == '23:45') {
        div_id = "div_" + event_day + "_" + string_from_date(event_start_time);
        $(div_id).removeClassName('pastweek');
        $(div_id).addClassName('inactive');
    }
}

function place_worktime_div(work_times, appointment){
    for (l = 0; l < work_times.length; l++) {
        call_new_div(work_times[l][2], work_times[l][3], work_times[l][4], work_times[l][5], work_times[l][6], appointment);
    }
}

function call_new_div(work_day, start_time1, end_time1, start_time2, end_time2, appointment){
    if (work_day == 'N') {
        new_div('00:00', '23:45', appointment);
    }
    if (work_day == 'Y') {
        if (start_time1 != '') {
            new_div("00:00", start_time1, appointment);
        }
        if (start_time2 != '') {
            new_div(end_time1, start_time2, appointment);
            new_div(end_time2, '23:45', appointment);
        }
        else {
            new_div(end_time1, '23:45', appointment);
        }
    }
}

function parseDate(event_time){
    return new Date("January 6, 1972  " + event_time + ":00");
}

function initial_call(){
    if (_time_start != '' && _time_end != '') {
    
        for (i = 0; i < staff_Array.length; i++) {
        
            groups[i] = new Array();
            event_blocks = staff_Array[i][1];
            if (event_blocks.length > 0) {
                groups[i] = groupOverlappingEventElements(event_blocks);
            }
        }
        createDiv();
        //        renderEvents();
    }
    
}

function adjustOverlappingEvents(event_blocks){
    groups = groupOverlappingEventElements(event_blocks);
    for (z = 0; z < groups.length; z++) {
        var groupAmount = groups[z].length;
        var curGroup = groups[z];
        var newWidth = _colo_width / groupAmount;
        for (p = 0; p < curGroup.length; p++) {
            var elem = curGroup[p];
        }
    }
    
}

//  Find groups of overlapping events
function groupOverlappingEventElements(event_blocks){
    var lastEvent;
    var group = [];
    var currentGroup = [];
    var curEvent;
    var currentGroupStartTime = 0;
    var currentGroupEndTime = 0;
    var lastGroupEndTime = 0;
    for (k = 0; k < event_blocks.length; k++) {
        curEvent = event_blocks[k];
        currentGroupStartTime = event_blocks[k][10].getTime();
        currentGroupEndTime = event_blocks[k][11].getTime();
        
        // if current start time is lower than current endtime time than either this event is earlier than the group, or already within the group   
        if (event_blocks[k][10].getTime() < lastGroupEndTime) {
            continue;
        }
        // loop through all current weekday events to check if they belong to the same group
        for (j = 0; j < event_blocks.length; j++) {
            // check for same element and possibility to even be in the same group  note: somehow ($curEvent == $(this) doens't work 
            if (curEvent[0] == event_blocks[j][0] || currentGroupStartTime > event_blocks[j][10].getTime() + 1 || currentGroupEndTime < event_blocks[j][10].getTime() + 1) {
                continue;
            }
            //set new endtime of the group
            if (event_blocks[j][11].getTime() > currentGroupEndTime) {
                currentGroupEndTime = event_blocks[j][11].getTime();
            }
            // ain't we adding the same element
            if (currentGroup.indexOf(event_blocks[j]) == -1) {
                currentGroup.push(event_blocks[j]);
            }
        }
        // ain't we adding the same element
        if (currentGroup.indexOf(curEvent) == -1) {
            currentGroup.push(curEvent);
        }
        if (currentGroup.length) {
            currentGroup.sort(function(a, b){
                if ($(a)[10] > $(b)[10]) {
                    return 1;
                }
                else 
                    if ($(a)[10] < $(b)[10]) {
                        return -1;
                    }
                    else {
                        return ($(a)[11] - $(a)[10]) - ($(b)[11] - $(b)[10]);
                    }
            });
            group.push(currentGroup);
            currentGroup = [];
            lastGroupEndTime = currentGroupEndTime;
        }
        
        
    }
    return group;
}

// Find groups of overlapping events
function groupOverlappingEventElements_drop(event_blocks){
    event_blocks = event_blocks.sort(function(a, b){
        return $(a)[5] - $(b)[5]
    });
    var lastEvent;
    var group = [];
    var currentGroup = [];
    var curEvent;
    var currentGroupStartTime = 0;
    var currentGroupEndTime = 0;
    var lastGroupEndTime = 0;
    //	alert("event_blocks.length"+event_blocks.length)
    for (k = 0; k < event_blocks.length; k++) {
        curEvent = event_blocks[k];
        //		alert("event_blocks[k][10]--->>>"+event_blocks[k][10]+"\nevent_blocks[k][5]----"+event_blocks[k][5])+"\nevent_blocks[k][6]----"+event_blocks[k][6]
        currentGroupStartTime = event_blocks[k][5].getTime();
        currentGroupEndTime = event_blocks[k][6].getTime();
        // if current start time is lower than current endtime time than either this event is earlier than the group, or already within the group   
        if (event_blocks[k][5].getTime() < lastGroupEndTime) {
            continue;
        }
        // loop through all current weekday events to check if they belong to the same group
        for (j = 0; j < event_blocks.length; j++) {
            // check for same element and possibility to even be in the same group  note: somehow ($curEvent == $(this) doens't work 
            if (curEvent[10] == event_blocks[j][10] || currentGroupStartTime > event_blocks[j][5].getTime() + 1 || currentGroupEndTime < event_blocks[j][5].getTime() + 1) {
                continue;
            }
            //set new endtime of the group
            if (event_blocks[j][6].getTime() > currentGroupEndTime) {
                currentGroupEndTime = event_blocks[j][6].getTime();
            }
            // ain't we adding the same element
            if (currentGroup.indexOf(event_blocks[j]) == -1) {
                currentGroup.push(event_blocks[j]);
            }
        }
        // ain't we adding the same element
        if (currentGroup.indexOf(curEvent) == -1) {
            currentGroup.push(curEvent);
        }
        if (currentGroup.length) {
            currentGroup.sort(function(a, b){
                if ($(a)[5] > $(b)[5]) {
                    return 1;
                }
                else 
                    if ($(a)[5] < $(b)[5]) {
                        return -1;
                    }
                    else {
                        return ($(a)[6] - $(a)[5]) - ($(b)[6] - $(b)[5]);
                    }
            });
            group.push(currentGroup);
            currentGroup = [];
            lastGroupEndTime = currentGroupEndTime;
        }
        
        
    }
    return group;
}

function initial_day_call(){
    if (_time_start != '' && _time_end != '') {
        for (i = 0; i < staff_Array.length; i++) {
            groups[i] = new Array();
            event_blocks = staff_Array[i][1];
            if (event_blocks.length > 0) {
                groups[i] = groupOverlappingEventElements(event_blocks);
            }
        }
        createDayDiv();
    }
}

function initial_day_call_more(){
    if (_time_start != '' && _time_end != '') {
        for (i = 0; i < staff_Array.length; i++) {
            groups[i] = new Array();
            event_blocks = staff_Array[i][1];
            if (event_blocks.length > 0) {
                groups[i] = groupOverlappingEventElements(event_blocks);
            }
        }
        createDayDivnew();
    }
}

function view_for_today(){
    $('date').value = $('current_date').value;
    setDateSel('false');
    changeCalendar();
}

function upAndDown(value){
    $('value').value = value;
    setDateSel('true');
    changeCalendar();
}

function form_fields_reset(changed_date, view){
    $('date').value = changed_date;
    $('value').value = '';
    if (view == 'A') {
        $('calendar_view').value = 'A';
    }
    else 
        if (view == 'L') {
            $('calendar_view').value = 'L';
        }
    
}

function setDateSel(val){
    $('date_sel').value = val;
}

function changeCalendar(){

    if ($('staff')) {
        //alert("staff");
        if ($('staff').value == 'All Calendars') {
            //alert("All Calendars")
            $('dayview').style.display = "";
            $('otherview').style.display = "none";
            $('calendar_view').value = "D";
        }
        else {
            //alert("Else All Calendars")
            $('dayview').style.display = "none";
            $('otherview').style.display = "";
            if ($('calendar_view').value == "") 
                $('calendar_view').value = "M";
        }
    }
    if ($('calendar_view')) {
        if ($('calendar_view').value == "A" && $('staff').value != 'All Calendars') {
            $('header').style.display = "block";
        }
        else {
            $('header').style.display = "none";
        }
        reset_arrays();
        
        $('cal_form').request({
            onCreate: function(){
                RedBox.loading()
            },
            onComplete: function(){
                RedBox.hide_loading();
            }
        });
    }
    else {
        $('header').style.display = "none";
    }
}

function reset_arrays(){
    Droppables.drops.clear();
    if (staff_Array != null) {
        staff_Array.clear();
    }
    if (staff_time_slot != null) {
        staff_time_slot.clear();
    }
}

function check_for_end_time(dropped_id, element_id){
    actual_time = element_id.split("_");
    old_date = actual_time[3];
    old_start_time = actual_time[4];
    old_end_time = actual_time[5];
    actual_id = actual_time[2];
    
    target_time = dropped_id.split("_");
    new_date = target_time[1];
    new_start_time = target_time[2];
    var new_end_time = findEndTime(old_start_time, old_end_time, new_start_time);
    
    return (new_start_time < new_end_time);
}

function change_app_block_time_week(contaner_id, url, staff_id, date_str, element, token){
    element_id = element.id;
    actual_time = element_id.split("_");
    old_date = actual_time[3];
    old_start_time = actual_time[4];
    old_end_time = actual_time[5];
    actual_id = actual_time[2];
    
    target_time = contaner_id.split("_");
    new_date = target_time[1];
    new_start_time = target_time[2];
    var new_end_time = findEndTime(old_start_time, old_end_time, new_start_time);
    div_ele = $(element_id);
    info = div_ele.name.split("_");
	if(element.recur==false){
		open_recur_change_pop_up(contaner_id, staff_id, date_str, element, token,'week');
	}		
	else{
		if (info[0] == "app") {
	        customer_name = info[1];
	        ser_name = info[2];
	        ser_price = info[3];
	        cust_phone = info[4];
	        type = "appointment";
	        rescheduleDiv(staff_id, "drag", actual_id, old_start_time, old_end_time, type, "", "", "", old_date, old_date, ser_price, '', element.data, element.breakd, element.work1,element.recur, element.recur_id,element.recur_index,element.recur_count);
	        rescheduleDiv(staff_id, "drop", actual_id, new_start_time, new_end_time, type, customer_name, ser_name, cust_phone, new_date, new_date, ser_price, info[info.length - 1], element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
	    }
	    else {
	        type = "block"
	        block_name = info[1];
	        block_private = info[2];
	        date_duration = actual_time[6].split('-');
	        old_start_date = change_format(date_duration[0], '/', '-');
	        old_end_date = change_format(date_duration[1], '/', '-');
	        new_end_date = calculateNewEndDate(date_duration[0], date_duration[1], new_date);
	        rescheduleDiv(staff_id, "drag", actual_id, old_start_time, old_end_time, type, "", "", "", old_start_date, old_end_date, block_private, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
	        rescheduleDiv(staff_id, "drop", actual_id, new_start_time, new_end_time, type, block_name, element.desc, "", new_date, new_end_date, block_private, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
	    }
	    action = url + "?type=" + type + "&id=" + actual_id + "&date=" + new_date + "&s_time=" + new_start_time + "&e_time=" + new_end_time;
	    ////WriteFile("in change_app_block_time_week action : " + action + "<br/>");
	    new Ajax.Request(action, {
	        asynchronous: true,
	        evalScripts: true,
	        parameters: 'authenticity_token=' + encodeURIComponent(token)
	    });
	}
		
	
    
    
}

function handle_drag_drop_of_recur(option_recur,contaner_id, staff_id, date_str, element, token){
//	alert("handle_drag_drop_of_recur-->"+option_recur);
//	alert("contaner_id-->"+contaner_id+"   url-->  "+url+"   staff_id--->"+staff_id);
//	alert("date_str-->"+date_str+"   element-->  "+element+"   token--->"+token);
	
	element_id = element.id;
    actual_time = element_id.split("_");
    old_date = actual_time[3];
    old_start_time = actual_time[4];
    old_end_time = actual_time[5];
    actual_id = actual_time[2];
    
    target_time = contaner_id.split("_");
    new_date = target_time[1];
    new_start_time = target_time[2];
    var new_end_time = findEndTime(old_start_time, old_end_time, new_start_time);
    div_ele = $(element_id);
    info = element.name.split("_");
	
	var $elemSel = jQuery(document).find('[id *= \'recur_'+element.recur_id+'\']')
	
		if (info[0] == "app") {
	        customer_name = info[1];
	        ser_name = info[2];
	        ser_price = info[3];
	        cust_phone = info[4];
	        type = "appointment";
			if(option_recur=="cancel"){
				old_start_time = old_start_time.split(":");
				old_end_time = old_end_time.split(":");
				old_start_time = (old_start_time[0].length==1 ? '0'+old_start_time[0] : old_start_time[0]) + ':'+(old_start_time[1].length==1 ? old_start_time[1]+'0' : old_start_time[1]);
				old_end_time = (old_end_time[0].length==1 ? '0'+old_end_time[0] : old_end_time[0]) + ':'+(old_end_time[1].length==1 ? old_end_time[1]+'0' : old_end_time[1]);
				
				rescheduleDiv(staff_id, "drag", actual_id, old_start_time, old_end_time, type, "", "", "", old_date, old_date, ser_price, '', element.data, element.breakd, element.work1,element.recur, element.recur_id,element.recur_index,element.recur_count);
	        	rescheduleDiv(staff_id, "drop", actual_id, old_start_time, old_end_time, type, customer_name, ser_name, cust_phone, old_date, old_date, ser_price, info[info.length - 1], element.data, element.breakd, element.work1,element.recur, element.recur_id,element.recur_index,element.recur_count);
			}else if(option_recur=='all'){
				$elemSel.each(function(i) {
					
				actual_time1 = this.id.split("_");
				
				actual_id1 = actual_time1[2];
				
				old_date1 = actual_time1[3];	
							
				new_date1 = addDays(new Date(change_format(new_date, '-', '/')),this.recur_index-element.recur_index);
				new_date1 = convertDateToHyphen(new_date1);
				
				rescheduleDiv(staff_id, "drag", actual_id1, old_start_time, old_end_time, type, "", "", "", old_date1, old_date1, ser_price, '', this.data, this.breakd, this.work1,this.recur, this.recur_id,this.recur_index,this.recur_count);
	        	rescheduleDiv(staff_id, "drop", actual_id1, new_start_time, new_end_time, type, customer_name, ser_name, cust_phone, new_date1, new_date1, ser_price, info[info.length - 1], this.data, this.breakd, this.work1,this.recur, this.recur_id,this.recur_index,this.recur_count);
			   });
			   
			}else{
				rescheduleDiv(staff_id, "drag", actual_id, old_start_time, old_end_time, type, "", "", "", old_date, old_date, ser_price, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
	        	rescheduleDiv(staff_id, "drop", actual_id, new_start_time, new_end_time, type, customer_name, ser_name, cust_phone, new_date, new_date, ser_price, info[info.length - 1], element.data, element.breakd, element.work1,true, '','','');
				$elemSel.each(function(i) {
					this.recur_count -=1
					if(this.recur_index>element.recur_index){
						this.recur_index -=1
					}
				});
			}
			if(option_recur!='cancel'){
				new Ajax.Request(_change_recur_app + "?type=" + type + "&id=" + actual_id + "&date=" + new_date + "&s_time=" + new_start_time + "&e_time=" + new_end_time+"&option_recur="+option_recur, {
			        asynchronous: true,
			        evalScripts: true,
			        parameters: 'authenticity_token=' + encodeURIComponent(token)
		    	});
			}else
				return true;
	        
	    }
	    else {
	        type = "block";
	        block_name = info[1];
	        block_private = info[2];
	        date_duration = actual_time[6].split('-');
	        old_start_date = change_format(date_duration[0], '/', '-');
	        old_end_date = change_format(date_duration[1], '/', '-');
	        new_end_date = calculateNewEndDate(date_duration[0], date_duration[1], new_date);
			if(option_recur=="cancel"){
					old_start_time = old_start_time.split(":");
					old_end_time = old_end_time.split(":");
					old_start_time = (old_start_time[0].length==1 ? '0'+old_start_time[0] : old_start_time[0]) + ':'+(old_start_time[1].length==1 ? old_start_time[1]+'0' : old_start_time[1]);
					old_end_time = (old_end_time[0].length==1 ? '0'+old_end_time[0] : old_end_time[0]) + ':'+(old_end_time[1].length==1 ? old_end_time[1]+'0' : old_end_time[1]);
				 rescheduleDiv(staff_id, "drag", actual_id, old_start_time, old_end_time, type, "", "", "", old_start_date, old_end_date, block_private, '', element.data, element.breakd, element.work1,element.recur, element.recur_id,element.recur_index,element.recur_count);
	        	 rescheduleDiv(staff_id, "drop", actual_id, old_start_time, old_end_time, type, block_name, element.desc, "", old_start_date, old_end_date, block_private, '', element.data, element.breakd, element.work1,element.recur, element.recur_id,element.recur_index,element.recur_count);
			}else if(option_recur=='all'){
				$elemSel.each(function(i) {
				actual_time1 = this.id.split("_");
				actual_id1 = actual_time1[2];
				old_date1 = actual_time1[3];
				
				new_date1 = addDays(new Date(change_format(new_date, '-', '/')),this.recur_index-element.recur_index);
				new_date1 = convertDateToHyphen(new_date1);
				
//				alert("drag id--->"+actual_id+"  from----> "+old_start_date);
				rescheduleDiv(staff_id, "drag", actual_id1, old_start_time, old_end_time, type, "", "", "", old_date1, old_date1, block_private, '', this.data, this.breakd, this.work1,this.recur, this.recur_id,this.recur_index,this.recur_count);
//				alert("drop id--->"+actual_id+"  to----> "+new_date1);
	        	rescheduleDiv(staff_id, "drop", actual_id1, new_start_time, new_end_time, type, block_name, this.desc, "", new_date1, new_date1, block_private, '', this.data, this.breakd, this.work1,this.recur, this.recur_id,this.recur_index,this.recur_count);
			   });

			}else{
				//if only single element is chosen, should be removed from recurrence series and count of elements after this should decrease
				rescheduleDiv(staff_id, "drag", actual_id, old_start_time, old_end_time, type, "", "", "", old_start_date, old_end_date, block_private, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
	        	rescheduleDiv(staff_id, "drop", actual_id, new_start_time, new_end_time, type, block_name, element.desc, "", new_date, new_end_date, block_private, '', element.data, element.breakd, element.work1,true, '','','');
				$elemSel.each(function(i) {
					this.recur_count -=1
					if(this.recur_index>element.recur_index){
						this.recur_index -=1
					}
				});
			}
			
		if(option_recur!='cancel'){
			new Ajax.Request(_change_recur_block + "?type=" + type + "&id=" + actual_id + "&date=" + new_date + "&s_time=" + new_start_time + "&e_time=" + new_end_time+"&option_recur="+option_recur, {
		        asynchronous: true,
		        evalScripts: true,
		        parameters: 'authenticity_token=' + encodeURIComponent(token)
	    	});
		}else
			return true;
	       
	    }
	    
		
}
function calculateNewEndDate(OldStartDate, OldEndDate, NewStartDate){
    var O_date_start = new Date(OldStartDate);
    var O_date_end = new Date(OldEndDate);
    var temp_date = NewStartDate.split('-');
    var N_start_date = new Date(change_format(NewStartDate, '-', '/'));
    var date_difference = O_date_end.getTime() - O_date_start.getTime();
    var new_end_date = new Date(N_start_date.getTime() + date_difference);
    var newdatestart = new_end_date.getFullYear();
    month = new_end_date.getMonth() + 1;
    day = new_end_date.getDate();
    if (month <= 9) {
        newdatestart += '-0' + month;
    }
    else {
        newdatestart += '-' + month;
    }
    if (day <= 9) {
        newdatestart += '-0' + day;
    }
    else {
        newdatestart += '-' + day;
    }
    return newdatestart;
}

function change_format(event_date, split_by, replaced_to){
    event_day_arr = event_date.split(split_by);
    return event_day_arr[0] + replaced_to + event_day_arr[1] + replaced_to + event_day_arr[2];
}

function change_color(element, color){

    if (_color_var_for_drag && _color_var_for_drag == true) 
        element.style.backgroundColor = color;
}

function new_day_div(start, end, name, staff, color, width, left, ide, datesel, type){
    staff_ide = staff;
    //////alert(staff_ide);
    wid = (810 / staff_Array.length)
    
    var con_div_id = 'eventLayer_' + staff + '_' + datesel;
    ////WriteFile("IN newdaydiv con_div_id : " + con_div_id);
    var x = document.createElement('div');
    var y = document.createElement('div');
    var first_top = "div_" + staff + "_" + start;
    var last_top = "div_" + staff + "_" + end;
    var arr_start = $(first_top).positionedOffset();
    var arr_end = $(last_top).positionedOffset();
    if (end == _time_end) {
        if (_time_duration_unit == 30) {
            arr_end[1] = arr_end[1] + 21;//changed by pooja
        }
        else 
            if (_time_duration_unit == 15) {
                arr_end[1] = arr_end[1] + 19;
            }
    }
    id = "div_work_" + ide + "_" + staff + "_" + start + "_" + end;
    y.innerHTML = name;
    y.id = ide + '_' + staff_ide + '_' + datesel
    x.appendChild(y);
    //x.style.border = '1px solid black';
    x.style.backgroundColor = color;
    x.id = id;
    //    				if (type == 'off')
    //    					x.style.zIndex = 1010;   
    //    				else
    
    x.style.position = 'absolute';
    x.style.float = 'left';
    if (width == '' && left == '') {
        if (navigator.userAgent.indexOf("MSIE") != -1) {
            left = 0;
        }
        else {
            left = 0;
        }
        x.style.width = wid + 'px';
        x.style.left = left + 'px';
    }
    else {
        x.style.width = width + 'px'
        x.style.left = left + 'px'
    }
    
    x.style.opacity = '0.3'
    x.style.filter = "alpha(opacity=15)";
    
    
    x.style.fontSize = '9px';
    x.style.fontWeight = 'normal';
    x.style.height = (arr_end[1] - arr_start[1]) + 'px';
    x.style.top = arr_start[1] + 'px';
    $(con_div_id).appendChild(x);
}

function change_app_block_time_day(container_id, url, cal_id, element, token,cal_view){
    if(element.recur==false)
		open_recur_change_pop_up(container_id, cal_id, '',element, token,cal_view);
	else
    	change_app_block_time_day_part_2(container_id, url, cal_id, element, token, '',cal_view);
}

function change_app_block_time_day_part_2(container_id, url, cal_id, element, token, option_recur,cal_view){
    actual_time = element.id.split("_");
	
	old_start_time = actual_time[4].split(":");
	old_end_time = actual_time[5].split(":");
	
	old_start_time = (old_start_time[0].length==1 ? '0'+old_start_time[0] : old_start_time[0]) + ':'+(old_start_time[1].length==1 ? old_start_time[1]+'0' : old_start_time[1]);
	old_end_time = (old_end_time[0].length==1 ? '0'+old_end_time[0] : old_end_time[0]) + ':'+(old_end_time[1].length==1 ? old_end_time[1]+'0' : old_end_time[1]);
					
    actual_id = actual_time[2];
	
    target_time = container_id.split("_")
	
    new_start_time = target_time[2]
    var new_end_time = findEndTime(old_start_time, old_end_time, new_start_time);
	
    info = element.name.split("_");
	
	var action = '';
    if (info[0] == "app") {
        customer_name = info[1];
        ser_name = info[2];
        ser_price = info[3];
        cust_phone = info[4];
        type = "appointment";
		action = _change_recur_app;
		if(option_recur == 'cancel'){
			if(cal_view == 'Day'){
				rescheduleDayDiv(actual_time[3], "drag", actual_id, old_start_time, old_end_time, type, "", "", "", '', '', ser_price, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
        		rescheduleDayDiv(actual_time[3], "drop", actual_id, old_start_time, old_end_time, type, customer_name, ser_name, cust_phone, '', '', ser_price, info[info.length - 1], element.data, element.breakd, element.work1,element.recur, element.recur_id,element.recur_index,element.recur_count);
			}else{
				rescheduleNewDayDiv(actual_time[3], "drag", actual_id, old_start_time, old_end_time, type, "", "", "", '', '', ser_price, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
        		rescheduleNewDayDiv(actual_time[3], "drop", actual_id, old_start_time, old_end_time, type, customer_name, ser_name, cust_phone, '', '', ser_price, info[info.length - 1], element.data, element.breakd, element.work1,element.recur, element.recur_id,element.recur_index,element.recur_count);
			}
			
			
		}else{
			if(cal_view == 'Day'){
				rescheduleDayDiv(actual_time[3], "drag", actual_id, old_start_time, old_end_time, type, "", "", "", '', '', ser_price, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
	        	rescheduleDayDiv(target_time[1], "drop", actual_id, new_start_time, new_end_time, type, customer_name, ser_name, cust_phone, '', '', ser_price, info[info.length - 1], element.data, element.breakd, element.work1,true, '','','');
			}else{
				rescheduleNewDayDiv(actual_time[3], "drag", actual_id, old_start_time, old_end_time, type, "", "", "", '', '', ser_price, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
	        	rescheduleNewDayDiv(target_time[1], "drop", actual_id, new_start_time, new_end_time, type, customer_name, ser_name, cust_phone, '', '', ser_price, info[info.length - 1], element.data, element.breakd, element.work1,true, '','','');
			}
		}
    }
    else {
        type = "block"
        block_name = info[1];
        block_private = info[2];
        index = cal_arr[cal_id].length - 1;
        staff_name = cal_arr[cal_id][index];
        
		action = _change_recur_block;
		if(option_recur == 'cancel'){
			if(cal_view == 'Day'){
				rescheduleDayDiv(actual_time[3], "drag", actual_id, old_start_time, old_end_time, type, "", "", "", "", "", block_private, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
	        	rescheduleDayDiv(actual_time[3], "drop", actual_id, old_start_time, old_end_time, type, block_name, element.desc, staff_name, '', '', block_private, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);			
			}else{
				rescheduleNewDayDiv(actual_time[3], "drag", actual_id, old_start_time, old_end_time, type, "", "", "", "", "", block_private, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
	        	rescheduleNewDayDiv(actual_time[3], "drop", actual_id, old_start_time, old_end_time, type, block_name, element.desc, staff_name, '', '', block_private, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);							
			}
			
		}else{
			if(cal_view == 'Day'){
				rescheduleDayDiv(actual_time[3], "drag", actual_id, old_start_time, old_end_time, type, "", "", "", "", "", block_private, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
        		rescheduleDayDiv(target_time[1], "drop", actual_id, new_start_time, new_end_time, type, block_name, element.desc, staff_name, '', '', block_private, '', element.data, element.breakd, element.work1,true, '','','');
			}else{
				rescheduleNewDayDiv(actual_time[3], "drag", actual_id, old_start_time, old_end_time, type, "", "", "", "", "", block_private, '', element.data, element.breakd, element.work1,element.recur,element.recur_id,element.recur_index,element.recur_count);
        		rescheduleNewDayDiv(target_time[1], "drop", actual_id, new_start_time, new_end_time, type, block_name, element.desc, staff_name, '', '', block_private, '', element.data, element.breakd, element.work1,true, '','','');
			}
			
		}
        
    }
	if(option_recur == 'cancel'){
		return true;
	}else if(option_recur == ''){
	    action = url + "?type=" + type + "&id=" + actual_id + "&calendar_id=" + cal_id + "&s_time=" + new_start_time + "&e_time=" + new_end_time;
	}else if(option_recur == 'all' || option_recur == 'only'){
		action = action + "?type=" + type + "&id=" + actual_id + "&calendar_id=" + cal_id + "&s_time=" + new_start_time + "&e_time=" + new_end_time+"&option_recur="+option_recur;
	}
	
    new Ajax.Request(action, {
        asynchronous: true,
        evalScripts: true,
        parameters: 'authenticity_token=' + encodeURIComponent(token)
    });
}

function findEndTime(old_start_time, old_end_time, new_start_time){
    var duration_start_time = new Date("January 6, 1972  " + old_start_time + ":00");
    var duration_end_time = new Date("January 6, 1972  " + old_end_time + ":00");
    
    duration = (duration_end_time.getTime() - duration_start_time.getTime());//time diff is returned in milisec to convert in to min----changed by pooja
    var new_start_date = new Date("January 6, 1972  " + new_start_time + ":00");
    var new_end_date = new Date();
    new_end_date.setTime(new_start_date.getTime() + duration);
    
    var new_end_time = '';
    if (new_end_date.getHours() < 10) 
        new_end_time += "0" + new_end_date.getHours();
    else 
        new_end_time += new_end_date.getHours();
    
    minutes = new_end_date.getMinutes();
    minutes = minutes + (minutes % _time_duration_unit);
    if (minutes < 10) 
        new_end_time += ":0" + minutes;
    else 
        new_end_time += ":" + minutes;
    return new_end_time;
}

function findEndDate(old_start_date, old_end_date, new_start_date){

}

function Confirmcancel(action){
    //_link = "http://" + window.location.host + action;
    _link = action;
    
    if (_dirty_bit == true) {
        jQuery.prompt("Are you sure you want to cancel your changes?", {
            buttons: {
                Yes: true,
                No: false
            },
            top: 200,
            callback: processAction
        });
    }
    else {
        window.location.href = _link;
    }
}

function remove_work_div(event_layer_div){
    var parent1 = document.getElementById(event_layer_div);
    var thisChild = parent1.firstChild;
    div_to_remove = new Array();
    while (thisChild != parent1.lastChild) {
        if (thisChild.nodeType == 1) {
            ids = thisChild.id;
            var id_splitted = new Array();
            id_splitted = ids.split("_");
            if (id_splitted[1] == 'work') 
                div_to_remove.push(ids);
            
        }
        thisChild = thisChild.nextSibling;
    }
    if (thisChild.nodeType == 1) {
        ids = thisChild.id;
        var id_splitted = new Array();
        id_splitted = ids.split("_");
        if (id_splitted[1] == 'work') 
            div_to_remove.push(ids);
        
    }
    for (i = 0; i < div_to_remove.length; i++) {
        removeElement(event_layer_div, div_to_remove[i]);
    }
}

function checkDirtyBit(action, source){
    if (_dirty_bit == 1) {
        return true;
    }
    else {
        disable_buttons();
        if (source == 'Custview' && action != "") {
            if (navigator.appName == "Microsoft Internet Explorer") {
                window.document.execCommand('Stop');
            }
            else {
                window.stop();
            }
            window.location.href = action;
            return false;
        }
        else 
            if (source == 'Calview') {
                //RedBox.close();
                toggle_visibility_and_close();
                return false;
            }
        
    }
}

function setFocusMsg(){
    if ($('message')) 
        $('message').focus();
}

function htmlEntities(text){
    var i, character, letra, output = '';
    for (i = 0; i < text.length; i++) {
        character = text[i].charCodeAt(0);
        if ((character > 47 && character < 58) || (character > 62 && character < 127)) {
            output += text[i];
        }
        else {
            output += "&#" + character + ";";
        }
    }
    return output;
}

function copyData(name){
    var webite_name = "";
    var site_name = new Array();
    var site_name = $(name).value;
    for (var i = 0; i < site_name.length; i++) {
        var char_name = site_name.charAt(i);
        var keyDelete = char_name.charCodeAt(0);
        if ((keyDelete >= 97 && keyDelete <= 122) || (keyDelete >= 65 && keyDelete <= 90) || (keyDelete >= 48 && keyDelete <= 57)) {
            webite_name = webite_name + String.fromCharCode(keyDelete);
        }
    }
    $('business_mini_site_name').value = webite_name.toLowerCase();
    ;
}

function cancelAppWithoutDirtyBitCheck(action, token){
    _token = token;
    if (typeof view != 'undefined') {
        _urlBlock = action + "&view=" + view;
    }
    else {
        _urlBlock = action;
    }
    jQuery.prompt('Are you sure?', {
        buttons: {
            Yes: true,
            No: false
        },
        top: 200,
        callback: delete_confirmed
    });
}

function cancel_app(action, token){
    _token = token;
    if (typeof view != 'undefined') {
        _urlBlock = action + "&view=" + view;
    }
    else {
        _urlBlock = action;
    }
    if (($('target_url') != null) && (_dirty_bit == true)) {
        jQuery.prompt('Are you sure you want to navigate away from this page? You have made changes to the page. Are you sure you want to exit without saving?', {
            buttons: {
                Yes: true,
                No: false
            },
            top: 200,
            callback: delete_confirmed
        });
    }
    else 
        delete_confirmed('true');
}

function set_count_value(length){
    if ($('service_count_field')) 
        $('service_count_field').value = length;
}

function checkForService(action){
    if ($('service_count_field').value == 0) {
        jQuery.prompt('Please configure at least one service for your business.', {
            buttons: {
                Ok: false
            }
        });
    }
    else {
        window.location.href = action;
        return true;
    }
    
    
}

function setStatusAndSubmit(status, action, source, cust_detail){
    $('appointment_status').value = status;
    //	    changed for displaying pop-up before acceting /denying requested appointment
    var abcd = '';
    if (status == 'C') {
        $('app_form').request();
        //	        abcd += "<b> Are you sure you want to accept an appointment for "+cust_detail[1].replace(/[+]/g, " ")+" </b>";
    }
    else {
        abcd += "<b> Are you sure you want to deny an appointment for " + cust_detail[1].replace(/[+]/g, " ") + " </b>";
        
        jQuery.prompt(abcd, {
            buttons: {
                Yes: true,
                No: false
            },
            top: 200,
            callback: submitform
        });
    }
    
    //------------------------------end----------------------------------------
}

function submitform(btn){
    if (btn) {
        $('app_form').request();
    }
    else 
        return false;
}

function disable_buttons(){
    if ($('save') && $('cancel')) {
        $('save').disabled = true;
        $('cancel').disabled = true;
        $('save').style.color = "#999999";
        $('cancel').style.color = "#999999";
    }
    if ($('new_block_save') && $('new_block_cancel')) {
        $('new_block_save').disabled = true;
        $('new_block_cancel').disabled = true;
        $('new_block_save').style.color = "#999999";
        $('new_block_cancel').style.color = "#999999";
    }
    //	return true;
}

function enable_buttons(){

    if ($('save') && $('cancel')) {
        $('save').disabled = false;
        $('cancel').disabled = false;
        $('save').style.color = "#ffffff";
        $('cancel').style.color = "#ffffff";
        
    }
    if ($('new_block_save') && $('new_block_cancel')) {
        $('new_block_save').disabled = false;
        $('new_block_cancel').disabled = false;
        $('new_block_save').style.color = "#ffffff";
        $('new_block_cancel').style.color = "#ffffff";
    }
    //	return true;
}

function getScrollXY(){
    var scrOfY;
    if (typeof(window.pageYOffset) == 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
    }
    else 
        if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
        }
        else 
            if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
                //IE6 standards compliant mode
                scrOfY = document.documentElement.scrollTop;
            }
    return scrOfY;
}

function getScrollXYP(){
    var scrOfY;
    $("yscroll").scrollTop = $('scrollTopDiv').scrollTop;
    $("xscroll").scrollLeft = $('scrollTopDiv').scrollLeft;
    
}

function clearRetypepswd(conf_pass, password){
    if ($(conf_pass)) {
        if ($(conf_pass).value != $(password).value) {
            $(conf_pass).value = "";
			if ($('suggestion'))
	            $('suggestion').innerHTML = '' ; 
			if ($('suggest1'))
	            $('suggest1').innerHTML = '' ; 
			
        }    
    }
}

function changecolor(flag, link_id){
    if ($(link_id)) {
        $(link_id).disabled = flag;
        if ($(link_id).disabled == true) {
            $('roundButt_id').className = 'roundButt_dis-3'
            $('roundButt_id1').className = 'roundButt_dis-3'
        }
        else {
            $('roundButt_id').className = 'roundButt-3'
            $('roundButt_id1').className = 'roundButt-3'
        }
    }
}

function disableSubmit(){
    $('forgot_submit').disabled = true;
    $('forgot_submit').style.color = '#999999';
}

function display_info(){
    if ($('business_mini_site_directions_page').checked) 
        $('direction_info_id').style.display = '';
    else 
        $('direction_info_id').style.display = 'none';
}

function toggle_visibility_of_fields(mode){
    if (getInternetExplorerVersion() == '6') {
        if (mode == 'show') {
            if ($('calendar_view')) {
                if ($('staff')) 
                    $('staff').style.visibility = 'visible';
                if ($('calendar_view')) 
                    $('calendar_view').style.visibility = 'visible';
            }
            else {
                if ($('appointment_calendar_id')) 
                    $('appointment_calendar_id').style.visibility = 'visible';
                if ($('appointment_service_id')) 
                    $('appointment_service_id').style.visibility = 'visible';
            }
            
            
            
        }
        else {
            if ($('calendar_view')) {
                if ($('staff')) 
                    $('staff').style.visibility = 'hidden';
                if ($('calendar_view')) 
                    $('calendar_view').style.visibility = 'hidden';
            }
            else {
                if ($('appointment_calendar_id')) 
                    $('appointment_calendar_id').style.visibility = 'hidden';
                if ($('appointment_service_id')) 
                    $('appointment_service_id').style.visibility = 'hidden';
            }
        }
    }
}

function toggle_visibility_and_close(){
    toggle_visibility_of_fields('show');
    RedBox.close();
}

//  Function to check if mobile phone has been entered, when reminder / notify method set to Text / E-mail & Text
function check_mobile(element){
    mobile_phone = $("customer_mobile_phone").value
    method = element.value
    if ((method == "T") || (method == "B")) {
        if (mobile_phone == "") {
            jQuery.prompt('Please Enter your Mobile Number');
            element.value = "E";
            return false;
        }
    }
    
}

function toggle_show_hide(url_address, show, hide, token){
    Element.toggle(show);
    Element.toggle(hide);
    
    new Ajax.Request(url_address, {
        asynchronous: true,
        evalScripts: true,
        parameters: 'authenticity_token=' + encodeURIComponent(token)
    });
}

//  Function to alert staff if mobile no. has not been setup
function check_duration2_when_break(breakd, work2){
    if (breakd > 0 && work2 == 0) {
        jQuery.prompt('Sorry, but you cannot setup a break time if the second work period is 0 minutes', {
            buttons: {
                Ok: false
            }
        });
        if (navigator.appName == "Microsoft Internet Explorer") {
            window.document.execCommand('Stop');
        }
        else {
            window.stop();
        }
    }
    else {
        submit_group_form('');
    }
}

//  Function to alert staff if mobile no. has not been setup
function check_mobile_phone_when_calendar_configured(value, mobile_phone){
    if (value && $('staff_need_calendar').checked == 1 && mobile_phone == '') {
        jQuery.prompt('<div align="center">WARNING</div> You have set staff notification preferences to include Text messages, ' +
        'but have not setup a valid mobile phone for this staff member.', {
            buttons: {
                Close: false
            },
            callback: submit_group_form
        });
        if (navigator.appName == "Microsoft Internet Explorer") {
            window.document.execCommand('Stop');
        }
        else {
            window.stop();
        }
    }
    else {
        submit_group_form('');
    }
}

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;
}

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;
}

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);
}

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
}

function isDate(dtStr, year_digit){
    // Declaring valid date character, minimum year and maximum year
    var dtCh = "/";
    var daysInMonth = DaysArray(12)
    var pos1 = dtStr.indexOf(dtCh)
    var pos2 = dtStr.indexOf(dtCh, pos1 + 1)
    var strMonth = dtStr.substring(0, pos1)
    var strDay = 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) {
        if (year_digit == 2) 
            return "Please enter date in the format mm/dd/yy";
        else 
            return "Please enter date of birth in the format mm/dd/yyyy";
    }
    if (strMonth.length < 1 || month < 1 || month > 12) {
        return "Please enter a valid month";
    }
    if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]) {
        return "Please enter a valid day";
    }
    if (year_digit == 4 && (strYear.length != 4 || year == 0)) {
        return "Please enter a valid 4 digit year";
    }
    if (year_digit == 2 && (strYear.length != 2 || year == 0)) {
        return "Please enter a valid 2 digit year";
    }
    if (dtStr.indexOf(dtCh, pos2 + 1) != -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false) {
        return "Please enter a valid date";
    }
    return true
}

// Check if business name is entered, when agent type is 'B' or 'O'
/*function check_if_business_name_entered(form_id){
    if (($('agent_agent_type').value == 'B' || $('agent_agent_type').value == 'O') && $('agent_business_name').value == '') {
        jQuery.prompt("Please enter the business / organization you belong to");
        return false;
    }
    else { // Business name not a mandatory field; or Business name is not blank, so submit the form happily
        $(form_id).submit();
    }
}*/

// Function to change labels, when a particular value selected from agent type dropdown.
function check_agent_type(obj){
    if (obj.value == 'O') {
        $('agent_signup_business_name').style.display = 'block';
        $('agent_business_name_label').innerHTML = 'Organization Name';
        $('agent_contact_name_label').innerHTML = 'Contact Name';
    }
    else 
        if (obj.value == 'B') {
            $('agent_signup_business_name').style.display = 'block';
            $('agent_business_name_label').innerHTML = 'Business Name';
            $('agent_contact_name_label').innerHTML = 'Contact Name';
        }
        else {
            $('agent_signup_business_name').style.display = 'none';
            $('agent_contact_name_label').innerHTML = 'Name';
        }
    
}

function activeDeactiveConfirm(action, token, msg){
    _token = token;
    _urlBlock = action;
    jQuery.prompt(msg, {
        buttons: {
            Yes: true,
            No: false
        },
        top: 200,
        callback: active_deactive_confirmed
    });
}

function active_deactive_confirmed(btn){
    if (btn) {
        window.location.href = _urlBlock
        return false;
    }
}

//  Function to check if proper 'digits' are inserted for Agent ID, and delete un-necessary characters
function remove_junk_chars(obj){
    var content = $(obj).value;
    var val_returned = '';
    for (var i = 0; i < content.length; i++) {
        var char_name = content.charAt(i);
        var key_code = char_name.charCodeAt(0);
        if (key_code >= 48 && key_code <= 57) 
            val_returned += String.fromCharCode(key_code);
    }
    $(obj).value = val_returned;
}

function reset_keywords(target_url, token){
    if ($('business_search_tags') && target_url != "") {
        new Ajax.Updater('business_search_tags', target_url, {
            asynchronous: true,
            evalScripts: true,
            parameters: 'authenticity_token=' + encodeURIComponent(token)
        });
    }
    
}
 function getValidTime(target_url, token){
	// 	alert("target url-->"+target_url);
	if ($('staff_id').value != "" && $('service').value != "" && $('appt_date').value != "") {
		if (target_url != "") {
	        new Ajax.Request(target_url, {
	            asynchronous: true,
				onCreate: function(){
	                $('ajax_apinner').style.display = '';
	            },
	            onComplete: function(){
	                $('ajax_apinner').style.display = 'none';
	            },
	            evalScripts: true,
	            parameters: 'authenticity_token=' + encodeURIComponent(token)
	        });
	    }
	}else{
		render_time('not_change_time');
	}
	 
 }
 
 function render_time(str){
	parent_div = $('app_s_time');
	if(parent_div){
		unorder_list = parent_div.getElementsByTagName('ul');
		var valid_time_array = new Array();
		ul_ele = unorder_list[0];
		valid_time_array = str.split(",");
		line_items = ul_ele.getElementsByTagName('li');
	//	alert("parent_div---> "+parent_div+"  ul-->"+ul_ele+"  line_items-->"+line_items)
		for(var p=0; p< line_items.length ;p++){
	//		alert("line_items[p]-->"+line_items[p].TEXT_NODE+"line_items[p].value-->"+line_items[p].innerHTML)
			if(str !='not_change_time'){
				if (valid_time_array.indexOf(line_items[p].innerHTML) != -1 || line_items[p].innerHTML == '') {
		            line_items[p].style.color = "black";
		        }
		        else {
		            line_items[p].style.color = "gray";
		        }
			}else{
				line_items[p].style.color = "gray";
			}
			
		}
	}
	

 }
//This function returns 0 if dates are equal 1 if date >date 2, -1 if date 1<date2
function compareDates(value1, value2){
    var date1, date2;
    var month1, month2;
    var year1, year2;
    month1 = value1.getMonth();
    date1 = value1.getDate();
    year1 = value1.getFullYear();
    
    month2 = value2.getMonth();
    date2 = value2.getDate();
    year2 = value2.getFullYear();
    
    if (year1 > year2) 
        return 1;
    else 
        if (year1 < year2) 
            return -1;
        else 
            if (month1 > month2) 
                return 1;
            else 
                if (month1 < month2) 
                    return -1;
                else 
                    if (date1 > date2) 
                        return 1;
                    else 
                        if (date1 < date2) 
                            return -1;
                        else 


                            return 0;
}


function matchDate(id){
	if($('start_date') && $('end_date')){
		block_start_date = new Date($('start_date').value);
		block_end_date = new Date($('end_date').value);
//		alert("id--->"+id+"\nstart date value--->" + block_start_date + "block_end_date-->  "+block_end_date+"\ncomparison"+compareDates(block_start_date, block_end_date) );
		if(id=='start_date' && compareDates(block_start_date, block_end_date) == 1){
			$('end_date').value = $('start_date').value;
		}else if(id=='end_date' && compareDates(block_start_date, block_end_date) == 1){
			$('start_date').value = $('end_date').value ;
		}
	}
	
    
}

function get_details_for_payment(target_url,form_token){
	var checkedBox = document.getElementById('business_use_info_pref_data');
	if(checkedBox.checked){
		new Ajax.Request(target_url, {
	        asynchronous: true,
	        evalScripts: true,
	        parameters: 'authenticity_token=' + encodeURIComponent(form_token)
	    });
	}else{
		document.getElementById('business_bi_email').disabled  = false;
		document.getElementById('business_bi_address').disabled  = false;
		document.getElementById('business_bi_city').disabled  = false;
		document.getElementById('business_bi_state').disabled  = false;
		document.getElementById('business_bi_zip').disabled  = false;
		
	}
	
    return false;
}

function fill_details_for_payment(add, city,state,zip,email){
	document.getElementById('business_bi_email').value = email;
	document.getElementById('business_bi_email').disabled  = true;
	
	document.getElementById('business_bi_address').value = add;
	document.getElementById('business_bi_address').disabled  = true;
	
	document.getElementById('business_bi_city').value = city;
	document.getElementById('business_bi_city').disabled  = true;
	
	document.getElementById('business_bi_state').value = state;
	document.getElementById('business_bi_state').disabled  = true;
	
	document.getElementById('business_bi_zip').value = zip;
	document.getElementById('business_bi_zip').disabled  = true;
}

function clearFields(){
	document.getElementById('business_exp_year').value = "";
	document.getElementById('business_exp_month').value = "";
	document.getElementById('business_cc_number').value = "";
	document.getElementById('business_cc_type').value = "";
}

function show_payment_history(){
	jQuery.prompt('No Payment History.', {
            top: 200
        });
}

// Check if staff has entered customer E-mail ID
function check_if_email_entered( email )
{
    if(email == '')
        {
            jQuery.prompt("<div style='text-align: justify'>An email address is required for the customer to be able to go online and make appointments themselves" +
                                  " or to receive email notifications. You can add their email address later if you do not currently know it. " +
                                  "Do you want to save this customer record without an email address?</div>", {
            buttons: {
                Yes: true,
                No: false
            },
            top: 200,
            callback: submit_without_email
        });
    if (navigator.appName == "Microsoft Internet Explorer") {
            window.document.execCommand('Stop');
        }
        else {
            window.stop();
        }
    }
    else {
        //  E-mail has been entered, submit happily :-)
        check_if_dob_entered();
    }
}

function submit_without_email(btn)
{
    if(btn)
        {
            check_if_dob_entered();
        }
}

function toggle_recurrence_div(cus_msg, recur_url, app_url, model )
{  
setDirtyBit();
var form_id = (model == 'appointment') ? 'app_form' : 'new_block_form';
    if( $('recur_link_' + model).innerHTML == 'Make Recurring')
    {    
        $('recurrence_div_' + model).style.display = 'block';
        $('recurring_' + model).value = 'true';
        $('recur_link_' + model).innerHTML = 'Remove Recurrence';  
		if (form_id == 'app_form') {
			$(form_id).onsubmit = function(){
				{
					if (ask_for_new_customer(cus_msg)) {
						disable_buttons();
						new Ajax.Request(recur_url, {
							asynchronous: true,
							evalScripts: true,
							parameters: Form.serialize(this)
						});
					}
					return false;
				}
			};
		}
		else {
			$(form_id).onsubmit = function(){
				{
						disable_buttons();
						new Ajax.Request(recur_url, {
							asynchronous: true,
							evalScripts: true,
							parameters: Form.serialize(this)
						});
					return false;
				}
			};
		}
     }
     else
         {
            $('recurrence_div_' + model).style.display = 'none';
            $('recurring_' + model).value = 'false';
            $('recur_link_' + model).innerHTML = 'Make Recurring';    
			if (form_id == 'app_form') {
				$(form_id).onsubmit = function(){
					{
						if (ask_for_new_customer(cus_msg)) {
							disable_buttons();
							new Ajax.Request(app_url, {
								asynchronous: true,
								evalScripts: true,
								parameters: Form.serialize(this)
							});
						}
						return false;
					}
				};
			}
			else{
				$(form_id).onsubmit = function(){
					{
							disable_buttons();
							new Ajax.Request(app_url, {
								asynchronous: true,
								evalScripts: true,
								parameters: Form.serialize(this)
							});
						return false;
					}
				};
			}
        }
}

function toggle_content_div(model)
{       
    if($('recur_interval_type_w_' + model).checked == true)
    {
        $('month_' + model).style.display = 'none';
        $('week_' + model).style.display = 'block';
    }
    else if($('recur_interval_type_m_' + model).checked == true)
        {
       $('week_' + model).style.display = 'none';
       $('month_' + model).style.display = 'block';
        }
}

function change_current_day_checkbox_to_read_only( entered_date, model)
{
    var date_fields = entered_date.split('/');
    new_date = new Date( date_fields[0] + "/" + date_fields[1] + "/" +(parseInt(date_fields[2]) + 2000) );    
    
    var check_boxes_array = ['recur_sunday_on', 'recur_monday_on', 'recur_tuesday_on', 
                                            'recur_wednesday_on', 'recur_thursday_on', 
                                            'recur_friday_on', 'recur_saturday_on'];
                                        
     var day_names =  ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
     
     var weeks_in_month = [ '', 'First', 'Second', 'Third', 'Fourth', 'Last'];
     
     var days_in_month_array = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
     var current_year = new_date.getFullYear();
     
     // Check leap year
     if(( (current_year % 4 == 0) && (current_year % 100 != 0)) || (current_year % 400 == 0)) days_in_month_array[1] = 29;

     var current_mth = new_date.getMonth();
     var current_date = new_date.getDate();
     var current_day = new_date.getDay();
     var day_today = day_names[current_day];
     var curr_week = Math.ceil( current_date / 7);
     var freq_of_occurence_of_current_day = curr_week + Math.floor( (days_in_month_array[current_mth] - current_date) /7);
     
     var week_no = (curr_week == 4 && freq_of_occurence_of_current_day == curr_week ) ? weeks_in_month[ curr_week + 1] : weeks_in_month[ curr_week];
   
    var day_of_the_week_checkbox = check_boxes_array[current_day];
    if( $('recur_interval_type_w_' + model) ) //&& $('recur_interval_type_w_' + model).checked == true )
        {
                        // Clear already checked checkboxes
            for(var i=0; i < check_boxes_array.length; i++)
            {  
                var element_id = check_boxes_array[i];
                if (model != 'appointment')
                    element_id = element_id + "_block";
                if(jQuery("#" + element_id))
                    {  
                        jQuery("#" + element_id).unbind('click');
                        jQuery("#" + element_id).click(function(){setDirtyBit()});                        
			jQuery("#" + element_id).attr('checked', false);
		    }
            }
            if (model != 'appointment')
                day_of_the_week_checkbox = day_of_the_week_checkbox + "_block";
            jQuery("#" + day_of_the_week_checkbox ).attr('checked', true);
            jQuery("#" + day_of_the_week_checkbox).click(function(){
                 jQuery(this).attr('checked', true);
            });

     }
    var label_element = "day_radio_button";
     if (model != 'appointment')
         label_element = label_element + "_block";
     jQuery("#" + label_element).html('Day ' + parseInt(date_fields[1]));         
     var label_element = "day_text";
     if (model != 'appointment')
         label_element = label_element + "_block"; 
     jQuery("#" + label_element).html(day_today);
     
     var label_element = "week_type";
     if (model != 'appointment')
         label_element = label_element + "_block";
     jQuery("#" + label_element).html('');         
     var mth_option;
     jQuery("#" + label_element).append('<option value="' + (week_no == weeks_in_month[5] ? 'L' : curr_week) + '">' + week_no + '</option>');
     if( freq_of_occurence_of_current_day == 5 && curr_week == 4)
        {              
        jQuery("#" + label_element).append('<option value="L">' + weeks_in_month[ 5] + '</option>');
        }
         change_return_val_for_mth_type_radio_button(model, label_element);
}

function change_return_val_for_mth_type_radio_button(model, label_element)
{ 
    var radio_element = "recur_month_type_x";
     if (model != 'appointment')
         radio_element = radio_element +  "_block";
    jQuery('#' + radio_element).attr('value', jQuery("#" + label_element).val());
}

function find_total_no_of_checkboxes()
{

var inputs = document.getElementsByTagName("input");
var check_boxes_array = [];
var checked = [];
for(var i=0; i< inputs.length; i++)
    {
        
      if (inputs[i].type == "checkbox" && inputs[i].name != 'addnewcustomer') {  
        check_boxes_array.push(inputs[i]);  
        if (inputs[i].checked) {  
        checked.push(inputs[i]);  
        }  
    }  
    }
}

function check_for_recurring(form_id, recurrence_url)
{   
    if ($('recurring').value == 'true'){
        check_for_checked_checkboxes();
           $(form_id).action = recurrence_url;
           $(form_id).request();
           return false;
    }    
}
function check_for_checked_checkboxes()
{
    var i=0, j = 0;
    var check_boxes_array = ['recur_sunday_on', 'recur_monday_on', 'recur_tuesday_on', 
        'recur_wednesday_on', 'recur_thursday_on', 
        'recur_friday_on', 'recur_saturday_on'];
    
    for( var j= 0; j < check_boxes_array.length; j++)      
    {
            if( $(check_boxes_array[j]).checked == true)
                i ++;
    }
    $('checked_check_boxes').value = i;
}
function reset_font_config(){
	jQuery('#business_font_face').val('Verdana');
	jQuery('#business_font_size').val('12')
	jQuery('#business_font_align').val('left')
    cust_ele = document.getElementById('Font_Color');
		cust_ele.value = '000000';
		cust_ele.style.backgroundColor = '#000000';
		cust_ele.style.color = '#ffffff';
}

/* function for resizing the iframe based on content of iframe for edit profile page on widget */
function resizeIframe(parent_iframe, newHeight) {
  document.getElementById(parent_iframe).style.height = parseInt(newHeight) + 'px';  
  if (parent_iframe == 'future_app_iframe') {
      document.getElementById('app_history_iframe').src = '/widget/appointment_history?collapsed=true'
      document.getElementById('msg_history_iframe').src = '/widget/message_history?message_collapsed=true'
      document.getElementById('app_history_iframe').style.height = '40px';
      document.getElementById('msg_history_iframe').style.height = '40px';
  }
  else if (parent_iframe == 'app_history_iframe') {
      document.getElementById('future_app_iframe').src = '/widget/future_appointments?appt_collapsed=true'
      document.getElementById('msg_history_iframe').src = '/widget/message_history?message_collapsed=true'
      document.getElementById('msg_history_iframe').style.height = '40px';
      document.getElementById('future_app_iframe').style.height = '40px';
  }
  else {
      document.getElementById('future_app_iframe').src = '/widget/future_appointments?appt_collapsed=true'
      document.getElementById('app_history_iframe').src = '/widget/appointment_history?collapsed=true'
      document.getElementById('app_history_iframe').style.height = '40px';
      document.getElementById('future_app_iframe').style.height = '40px';
  }
}

function setWidgetHeight() {
    if (document.getElementById('collapse_future_appointments')) {
        if (document.getElementById('collapse_future_appointments').style.display == 'block' || document.getElementById('collapse_future_appointments').style.display == '') {
            document.getElementById('widgetDiv').style.height = (parseInt(document.getElementById('widgetDiv').style.height) - parseInt(100)) + 'px';
        }
        else {
            document.getElementById('widgetDiv').style.height = (parseInt(document.getElementById('widgetDiv').style.height) + parseInt(100)) + 'px';
        }
    }
}

function setWidgetHeightOnLoad() {
    if (document.getElementById('collapse_future_appointments')) {
        if ((document.getElementById('collapse_future_appointments').style.display == 'block') || (document.getElementById('collapse_future_appointments').style.display == '')) {
            document.getElementById('widgetDiv').style.height = (parseInt(document.getElementById('widgetDiv').style.height) - parseInt(100)) + 'px';
        }
    }
}

function handle_conflicts( conflict_array, url, event )
{    
    var title = event == 'block' ? 'Block Time' : 'Appointment'
    var str = '';
   _conflict_accept_url = url; 
    for(var i=0; i< conflict_array.length ; i++)
        {
          str = str.concat( '<tr style="background: none repeat scroll 0% 0% rgb(245, 245, 245);">')
            for(var j =0; j<conflict_array[i].length; j++)
             {     
                 str =   str.concat('<td align="left" style="width:50px;">  <span>' + conflict_array[i][j] + '</span>   </td> ');
            }
           str =  str.concat('<td align="center"  style="width:50px;">  <input type="checkbox" checked="checked" id="app_' + i + '"  name="app_' + i + '" value="Y" >' +'</td></tr>');
    
    }
    var height_str = conflict_array.length >= 13 ? 'height:300px' : 'height:auto';
    msg = '<div align="center">Recurring ' + title +  ' Process</div>' +             
            '<div style="color: rgb(0, 0, 0); float: left; font-size: 11px; font-weight: bold;  margin:5px; text-align: left;">' +
              'These conflicts are about to be created.  Please review and select OK to proceed.' +
            '</div>' + 
            '<form action=" '  + url + '" id="conflict_form">' +            
              '<table cellspacing="0" cellpadding="0" border="0" style="width:385px; margin:0" class="popTableReq">' +
                '<thead>' +
                  '<tr>'    +    
                    '<th align="center" valign="middle"  style="width:50px;"> Date </th>' +        
                    '<th align="center" valign="middle"  style="width:50px;">  Day </th>'  +      
                    '<th align="center" valign="middle"  style="width:50px;">  Time </th>'   +     
                    '<th align="center" valign="middle"  style="width:50px;">  Conflict Status </th>'        +
                    '<th align="center" valign="middle"  style="width:50px;">   Skip </th>' +    
                  '</tr>' +
                '</thead>' +
               '</table>' +
                
                '<div style="overflow-y:auto;overflow-x:hidden;'+ height_str + ' ">' +  
                '<table cellspacing="0" cellpadding="0" border="0" style="width:385px; margin:0" class="popTableReq">' +
                '<tbody style="margin:0; overflow-y:auto; overflow-x:hidden;">' +  str +        
                  '</tbody>' +
                  '</table>'+
                  '</div></form>' +
            '<div class="clear"></div>';
            
        
    jQuery.prompt( msg, {
         buttons: {
            OK: true,
            Cancel: false
        },
        callback: response_post_for_conflict
        });
    
}

function response_post_for_conflict(btn, message, f){                
    if (btn) {               
new Ajax.Request(_conflict_accept_url, {
							asynchronous: true,
							evalScripts: true,
							parameters: f
						});
            }
    else {
        new Ajax.Request('/recurrences/clear_session', {
							method: 'get'
						});
            
        enable_buttons();
        return false;
        }
}

// Function will display information about skipped conflicts
function display_skipped_conflicts(conflict_array, override_array, url) {
  var str = '';
  _cust_url = url;
   if (override_array.length > 0) {
       str = str.concat( 'These days were skipped: ');
       for(var i=0; i< override_array.length ; i++) {
            str =  str.concat('<span>' + override_array[i] + '</span>');
            if (i != (override_array.length -1)) {
                str =  str.concat(', ');
            }
       }
       str =  str.concat('<br><br>');
   }
   if (conflict_array.length > 0) {
       str = str.concat( 'Conflicts were created on these days: ');
       for(var i=0; i< conflict_array.length ; i++) {
            str =  str.concat('<span>' + conflict_array[i] + '</span>');
            if (i != (conflict_array.length -1)) {
                str =  str.concat(', ');
            }
       }
       str =  str.concat('<br><br>');
   }
   str = str.concat('This is simply a reminder for you to manually handle these exceptions.');
   jQuery.prompt(str, {
            buttons: {
                Ok: true
            },
            callback: response_skipped_conflicts
        });
        if (navigator.appName == "Microsoft Internet Explorer") {
            window.document.execCommand('Stop');
        }
        else {
            window.stop();
        }
}

function response_skipped_conflicts(btn) {
    
    if (btn && _cust_url != '') {                
        window.location.href = _cust_url;
        return true;
    }    
}

function addDays(myDate,days) {
//	alert("mydate--->"+new Date(myDate.getTime() + days*24*60*60*1000))
	 return new Date(myDate.getTime() + days*24*60*60*1000);

}
function convertDateToHyphen(date){
	 var newdatestart = date.getFullYear();
    month = date.getMonth() + 1;
    day = date.getDate();
    if (month <= 9) {
        newdatestart += '-0' + month;
    }
    else {
        newdatestart += '-' + month;
    }
    if (day <= 9) {
        newdatestart += '-0' + day;
    }
    else {
        newdatestart += '-' + day;
    }
    return newdatestart;
}

// Function for refershing the iframe from child frame
function refreshIframe(url) {
    parent.location = url;
}

function cancelEditProfile(url) {
    window.location.href = url;
}

function populateCustomOptions(from, custom_field_id, field_type) {
    var type = $('custom_field_field_type').value
    if (custom_field_id != '' && from == 'populate') {
        return check_field_type (field_type, type);
    }
    
    if (from == 'populate') {
        jQuery('#custom_options').html('');
    }
    if (type == 'M') {
        $('add_option').style.display = 'block';
        $('custom_options').style.display = 'block';
        add_multi_selection_row(from);
    }
    else if (type == 'D') {
        $('add_option').style.display = 'block';
        $('custom_options').style.display = 'block';
        add_drop_down_row(from);
    }
    else {
        $('add_option').style.display = 'none';
        $('custom_options').style.display = 'none';
    }
    return false;
}

function add_multi_selection_row(from) {
    //var row_id = jQuery('div#custom_field_options').size();
    var row_id = jQuery('div#custom_options div :last').attr('option_id');
    if (typeof(row_id) == 'undefined')
        row_id = 0; 
    var html = '';
    if (from == 'populate') {
        html += '<div><div style="width:50px;float:left;">Selected</div>';
        html += '<div style="padding-left:10px;float:left;">Options</div></div>';
        html += '<div class="clear"></div>';
    }                
    html += '<div id="custom_field_options">';
    html +=  '<div class="custom_options_outer_div">';
    html +=  '<input name="custom_field[custom_options_attributes][' + row_id + '][field_default]" value="0" type="hidden">';
    html +=  '<input id="custom_field_custom_options_attributes_' + row_id + '_field_default" name="custom_field[custom_options_attributes][' + row_id + '][field_default]" value="1" type="checkbox">';
    html +=  '</div>';
    html +=  '<div class="custom_options_inner_div">';
    html +=  '<input id="custom_field_custom_options_attributes_' + row_id + '_field_option" name="custom_field[custom_options_attributes][' + row_id + '][field_option]" size="30" type="text">';
    html +=  '</div>';
    
    //if (row_id > 0) {
    if (from != 'populate') {          
        html += '<a title="Are you sure you want to remove this radio button option?" class="remove" href="#">Remove</a>';
    }
    html += '</div>';

    jQuery('div#custom_options').append(html);
    jQuery('div#custom_options div :last').attr('option_id', parseInt(row_id) + 1);
    
    jQuery('.remove').live('click', function(){
            jQuery(this).parent('div').animate({opacity: 'hide', height: 'hide', marginBottom: '0px'}, 'fast', function () {
                jQuery(this).remove();
            });
            return false;
    });
}

function add_drop_down_row(from) {
     //var row_id = jQuery('div#custom_field_options').size();
    var row_id = jQuery('div#custom_options div :last').attr('option_id');
    if (typeof(row_id) == 'undefined')
        row_id = 0; 
    var html = '';
    if (from == 'populate') {
        html += '<div class="clear"><div style="width:50px;float:left;">Selected</div>';
        html += '<div style="padding-left:10px;float:left;">Options</div></div>';
    }                
    html += '<div id="custom_field_options">';
    html +=  '<div class="custom_options_outer_div">';
    html +=  '<input name="custom_field[custom_options_attributes][' + row_id + '][field_default]" value="0" type="hidden">';
	html += '<input id="field_default_' + row_id + '" name="field_default" value="1" type="radio" class="radio_button">';
	html += '<input class="field_default" id="custom_field_custom_options_attributes_' + row_id + '_field_default" name="custom_field[custom_options_attributes][' + row_id + '][field_default]" value="0" type="hidden">';
    html +=  '</div>';
    html +=  '<div class="custom_options_inner_div">';
    html +=  '<input id="custom_field_custom_options_attributes_' + row_id + '_field_option" name="custom_field[custom_options_attributes][' + row_id + '][field_option]" size="30" type="text">';
    html +=  '</div>';
    
    //if (row_id > 0) {
    if (from != 'populate') {    
        html += '<a title="Are you sure you want to remove this radio button option?" class="remove" href="#">Remove</a>';
    }
    html += '</div>';
    
    jQuery('div#custom_options').append(html);
    jQuery('div#custom_options div :last').attr('option_id', parseInt(row_id) + 1);
    
    jQuery('.remove').live('click', function(){
            jQuery(this).parent('div').animate({opacity: 'hide', height: 'hide', marginBottom: '0px'}, 'fast', function () {
                jQuery(this).remove();
            });
            return false;
    });
    jQuery('.radio_button').live('click', function(){
        jQuery('#custom_options').find('.field_default').each(function () {
            jQuery(this).val(0);
        });
        jQuery(this).parent('div').find('.field_default').val(1);
    });
}

function check_field_type (field_type, type) {
   str = "You can't change the field type to any other field type";
   switch (field_type) {
     case 'M':
                jQuery.prompt(str, {
                    buttons: {
                            Ok: true
                    },
                    top: 200
                });
                $('custom_field_field_type').value = field_type;
                return false;
                break;
     case 'D' :
                jQuery.prompt(str, {
                    buttons: {
                            Ok: true
                    },
                    top: 200
                });
                $('custom_field_field_type').value = field_type;
                return false;
                break;
     case 'O' :
                jQuery.prompt(str, {
                    buttons: {
                            Ok: true
                    },
                    top: 200
                });
                $('custom_field_field_type').value = field_type;
                return false;
                break;
     case 'C' :
                jQuery.prompt(str, {
                    buttons: {
                            Ok: true
                    },
                    top: 200
                });
                $('custom_field_field_type').value = field_type;
                return false;    
                break;
     case 'L' :
                if (type != 'B') {
                    jQuery.prompt("You can change only to field type Text Box", {
                    buttons: {
                            Ok: true
                    },
                    top: 200
                    });
                    $('custom_field_field_type').value = field_type;
                    return false;    
                    break;
                }
                else {
                    break;
                }
     case 'B' :
                if (type != 'L') {
                    jQuery.prompt("You can change only to field type Text Line", {
                    buttons: {
                            Ok: true
                    },
                    top: 200
                });
                    $('custom_field_field_type').value = field_type;
                    return false;    
                    break;
                }
                else {
                    break;
                }    
     default: return true;
  }    
}

function save_custom_form(){
    $('custom_field_form').request();
}

function open_details_for_payment(base_payment,total_cal_count, additional_cal_count, cost_per_cal){
	total_amt = base_payment+(additional_cal_count*cost_per_cal);
	str = "<table width='100%'>";
	str += "<tr><td width='60%'>Number of calendars</td><td width='40%'>"+total_cal_count+"</td></tr>";
	str += "<tr><td width='60%'>Base payment</td><td width='40%'>$"+base_payment+" </td></tr>";
	str += "<tr><td width='60%'>Additional calendars</td><td width='40%' >$"+additional_cal_count*cost_per_cal+"</td></tr>";
	str += "<tr><td width='60%'>Total monthly payment</td><td width='40%'>$"+total_amt+"</td></tr>";
	str += "</table>"
	jQuery.prompt(str, {
            buttons: {
                Ok: true
            },
            top: 200
        });
}

function save_reason_and_hide_text(action,hide_in_response){
	if($('business_unsubscribe_reason')){
		reason = $('business_unsubscribe_reason').value;
		if(hide_in_response=='yes'){
			action = window.location.protocol + "//" + window.location.host + action+"?reason="+reason+"&hide_div="+hide_in_response;
		}else{
			if($('unsubs_reason').style.display=='none')
				hide_in_response = 'yes';
			action = action+"&hide_div="+hide_in_response;
		}
		if(reason != ""){
			new Ajax.Request(action, {
				asynchronous: true,
				evalScripts: true
			});
			
		}else if(hide_in_response=='yes'){
			show_hide_div('unsubs_reason','none');
		}
	}
	
}

function unsubscribe_business(id,show_hide,action){
	unsubs_hit_value = $('unsubs_hit_count').value;
	reason = $('business_unsubscribe_reason').value;
	_save_reason_action = window.location.protocol + "//" + window.location.host + action+"?reason="+reason;
	if(unsubs_hit_value==0){
		$('unsubs_hit_count').value =1;
		show_hide_div('unsubs_reason','');
	}else if(unsubs_hit_value==1){
		jQuery.prompt("Are you sure you wish to deactivate your account?", {
            buttons: {
                Yes: true,
                No: false
            },
            top: 200,
            callback: unsubscribeAction
        });
		
		
	}
}

function unsubscribeAction(btn){
	if(btn){
		document.formpayment.submit();
	}else{
		save_reason_and_hide_text(_save_reason_action,'no');
	}
	
}

function show_hide_div(id,show_hide){
	if($(id)){
		$(id).style.display = show_hide;
	}
}

function saveInfoAndRedirectsToCustomFields(action) {
    _action = action;
    _link =  window.location.protocol + "//" + window.location.host + action;
    if ((_dirty_bit == true)) {
        $('target_url').value = action;
        document.formone.submit();
    }
    else { 
       window.location.href = _link;
    }
}

function checkAgentLandingPage(){
    if ($('agent_landing_page_web_address').value == '') {
        $('suggest').innerHTML = '';
        return false;
    }
    else {
        return true;
    }
}

function checkLandingAddress(name){
    var webite_name = "";
    var site_name = new Array();
    var site_name = $(name).value;
    for (var i = 0; i < site_name.length; i++) {
        var char_name = site_name.charAt(i);
        var keyDelete = char_name.charCodeAt(0);
        if ((keyDelete >= 97 && keyDelete <= 122) || (keyDelete >= 65 && keyDelete <= 90) || (keyDelete >= 48 && keyDelete <= 57)) {
            webite_name = webite_name + String.fromCharCode(keyDelete);
        }
    }
    $('agent_landing_page_web_address').value = webite_name.toLowerCase();
}

function reset_options(){
	jQuery('div#custom_options input:checked').each(function(){
				jQuery(this).attr('checked', false);
				jQuery(this).parent('div').find('.field_default').each(function()
						{
						jQuery(this).val(0);
				});
	});
}


function check_for_landing_page(element_id)
{
	if ($(element_id).checked == false) {
		Element.remove('balloon');
		Element.remove('closeButton');
	}
}

function Checkfileformat(){
    var fup = document.getElementById('agent_landing_page_graphic');
    var fileName = fup.value;
    var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
    if (fileName == '' || ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "PNG" || ext == "BMP" || ext == "TIF" || ext == "png" || ext == "bmp" || ext == "tif" || ext == "JPG") {
		 document.formone.submit();
    }
    else {
      jQuery.prompt("Please choose image files of format gif/png/jpg/bmp/tif  for home picture ");
      fup.focus();
      return false;
    }
  }
