﻿var appPath = pageParams.appPath;
var IsLoggedIn = pageParams.serverIsLoggedIn;
var memberFullName = pageParams.memberFullName;
var secondPaletteColor = pageParams.secondPaletteColor;
var imagesUrl = pageParams.imagesUrl;
var eee;

    window.onload = function(){
    
//init();//init Yahoo calendar
$('target').innerHTML = loadLoaderIMG();


//if(IsLoggedIn == 'True')
//{
//    if ($('cont_login'))
//    $('cont_login').style.display = 'none';
//    jsonObj.asyncWithCallback('jsonHandler','getPersonalInfo',null,'callbackGetUserInfo');
//    
//}
//else {
    if ($('cont_login'))
    $('cont_login').style.display = '';
//}
start();

};


var noAvailable = Resources.sorryThereAreNoAvailableTimeSlots;
//var isLoggedIn = pageParams.isLoggedIn; 
function callbackLogout(response)
{
    $('cont_userName').innerHTML = "<a href='" + Resources.DomainURL + "/pages/a/businessregistration.aspx'>" + Resources.registerYourBusinessItFree + "</a>, " + Resources.or +
            " <a href='<%=appPath %>/pages/a/login.aspx'>" + Resources.home_lblLogin + "</a> " + Resources.ifAlreadyMemeber;
            IsLoggedIn = "False";
            if($('confirmBtn'))
                $('confirmBtn').className = 'confirmBtnHide';
            if ($('cont_login'))
            $('cont_login').style.display = '';

}
var clientData = new Object();
function login(id)
{
    var params = checkFields(id);
    if(params!=null)
    {
        params.push(new Date().getTimezoneOffset());
        jsonObj.asyncWithCallback('jsonHandler','LoginReturnUserInfo',params,'callbackLogin');
    }
}
function callbackLogin(response)
{//debugger
    if(response)
    {
        if(response.result!='' && response.result!='{}' && response.result!='[]')
        {//getPersonalInfoFromSession
        
            clientData = eval('(' + response.result+')');
            if(clientData.BusinessList)
            {
                var memberFullName = clientData.SchedulyUserInfo.firstName + ' ' + clientData.SchedulyUserInfo.lastName;
                $('cont_userName').innerHTML = Resources.hi + " " + memberFullName +
                    "<span class='brackets'>[</span><a id='weekly' class='tpicker' href='"+appPath+"/pages/e/welcome.aspx'" +
                    ">" + clientData.BusinessList[0].businessTitle + " " + Resources.upperLinks_Account +
                        "</a><span class='spacer'>|</span><a class='tpicker' href='" + appPath + "/pages/b/myappointments.aspx'>" + Resources.home_lblMyAppointments + "</a>" +
                        "<span class='spacer'>|</span><a class='tpicker' href='javascript://' onclick='logout()' >" + Resources.upperLinks_Logout + "</a><span class='brackets'>]</span>";
            }
            else
            {
                $('cont_userName').innerHTML = Resources.hi + " " + memberFullName +
                    "<span class='brackets'>[</span><a class='tpicker' href='" + appPath + "/pages/b/myappointments.aspx'>" + Resources.home_lblMyAppointments + "</a>" +
                        "<span class='spacer'>|</span><a id='weekly' class='tpicker' href='" + appPath + "/pages/d/memberinfo.aspx'>" + Resources.home_lblSettings + "</a>" +
                        "<span class='spacer'>|</span><a class='tpicker' href='javascript://' onclick='logout()' >" + Resources.upperLinks_Logout + "</a><span class='brackets'>]</span>";
            }
            
            IsLoggedIn = "True";
            FullName = clientData.SchedulyUserInfo.firstName + ' ' + clientData.SchedulyUserInfo.lastName;
            if($('confirmBtn'))
                $('confirmBtn').className = 'confirmBtn';
//            userMsgDisplayer('login',$('cont_login'));
            $('loginDetails').style.display = 'none';

            removeMsg();
            if ($('cont_login'))
            $('cont_login').style.display = 'none';
        }
        else
        {
            userMsgDisplayer('notLogin',$('loginMsg'));
        }
    }
}

//function registerUser(id)
//{
//    
//    var params = checkFields(id);
//    if(params!=null)
//    {
//        jsonObj.asyncWithCallback('jsonHandler','CreateUserReturnUserInfo',params,'callbackLogin');
//    }
//    else
//    {
//        
//    }
//}

function checkAvailability(id)
{
    
    $('loader').innerHTML = loadLoaderIMG();
   var email = $(id).value;
   if(!EmailCheck(email))
    {
        $('loader').innerHTML = 'invalid email';
        $('loader').style.color = 'red';
        return;
    }
    if(email=='')return;
    var params = new Array();
    params.push("'" + email + "'");
    jsonObj.asyncWithCallback('jsonHandler','CheckUserNameAvailability',params,'callbackCheckAvailability');
}
function callbackCheckAvailability(response)
{//debugger
    if(!response)
    {
       $('loader').innerHTML = 'not available';
       return;
    }//alert(response.result )
    if(response.result == true)
    {
        $('loader').innerHTML = 'not available';
        $('loader').style.color = 'red';
    }
    else
    {
        $('loader').innerHTML = 'available';
        $('loader').style.color = 'green';
    }
    
}
function setDateTimeAttribute(obj,startTime,endTime)
{
    obj.setAttribute('dt',getSelectedDate().toStringMMDDYYYY());
    obj.setAttribute('s_time',startTime);
    obj.setAttribute('e_time',endTime);
}
function setAppointment(id) {
    if ($('selection')) {
        if ($('selection').style.display == 'none') {
            $('selection').style.display = 'block';
            $('selection').setAttribute('style', 'background:#d7e2f5;');
        }
    }

    
    
    var lastShow = YAHOO.util.Dom.getElementsByClassName('selected', 'a');
    lastShow[0]?lastShow[0].className = 'none':null;
    $(id).className = 'selected';
    ($('innerCont')?$('innerCont').style.backgroundColor = 'transparent':null);
    
    //aRow_TIME_STAMP-SHORT_DT-SERVICE_ID
    var dt = id.split('_')[1];
    dt = dt.split('-');
    var showDT = document.createElement('p');
    showDT.innerHTML = getSelectedDate().toStringFullDate();
    var showT = document.createElement('p');
    showT.innerHTML = dt[0] + " - " + dt[1];
    var appointmentCont = document.createElement('div');
    var innerCont = document.createElement('div');
    innerCont.id = 'innerCont';
    innerCont.className = 'innerContBP';
    var txt = document.createElement('div');
//    var exp = document.createElement('p');
//    exp.innerHTML = "By clicking the 'Grab it!' button you set the appointment for the selected slot."
    //txt.appendChild(exp);
    var warrning = document.createElement('p');
    warrning.appendChild(document.createTextNode(Resources.GrabItHelp));//'(clicking on the \'Grab It!\' button will set you appointment with this business and notification will be send to you both.)'));
    warrning.className = 'grabItWarrning';
    txt.appendChild(showDT);//getSelectedDate().toDateString()));
    txt.appendChild(showT);
    
    txt.className = 'appointHour';
    txt.id = 'theDateTime';
    setDateTimeAttribute(txt,dt[0],dt[1]);
    innerCont.appendChild(txt);
    var btns = document.createElement('div');
    btns.id = 'confirmBtn';
    var nextPhase = document.createElement('div');
    nextPhase.id = 'nextPhase';
//    var cancel = document.createElement('a');
//    cancel.href = 'javascript://';
    //    cancel.innerHTML = 'cancel';
    var schedule;
    var btnUD;
    if (Resources.LangIso3Letters == 'eng') {
        schedule = document.createElement('img'); //('input');//('a');
        //schedule.type = 'button';
        schedule.src = Resources.ImagesDirectory + "buttons/grabIt1.png"; //.gif';

        schedule.setAttribute("altsrc", Resources.ImagesDirectory + "buttons/grabItHover1.png");
        //schedule.className = 'btnGrabIt'
        //schedule.href = '#';
        //schedule.innerHTML = 'grab it!';
        //schedule.value = 'Grab it!';
        
        schedule.setAttribute("onmouseover", "swapImgSrc('grabBtn')");
        schedule.setAttribute("onmouseout", "swapImgSrc('grabBtn')");

        //TODO: btnUD
        
    }
    else {
        schedule = document.createElement('input');
        schedule.type = 'button';
        schedule.value = Resources.GrabIt;
        schedule.className = 'grabItBtn';

//        btnUD = document.createElement('input');
//        btnUD.type = 'button';
//        btnUD.value = Resources.setAppointment3_userDetails;
//        btnUD.className = 'grabItBtn';
    }
    btnUD = document.createElement('input');
    btnUD.type = 'button';
    btnUD.value = Resources.setAppointment3_userDetails;
    btnUD.className = 'grabItBtn';
    
    schedule.id = 'grabBtn';
    schedule.setAttribute("onclick", "insertAppointment()");
    btnUD.id = 'btnUD';
    btnUD.setAttribute("onclick", "setUserDetails()");
    //  btns.appendChild(cancel);
    //Inputs: full name and email
    var inpts = document.createElement('div');
    inpts.className = 'confirmationInputs';
    inpts.id = 'clientDetails';
    var nameDiv = document.createElement('div');
    var emailDiv = document.createElement('div');
    var fullName = document.createElement('input');
    fullName.type = 'text';
    fullName.id = 'fullName';
    var email = document.createElement('input');
    email.type = 'text';
    email.id = 'email';
    var fullNameTxt = document.createElement('p');
    fullNameTxt.appendChild(document.createTextNode('Full Name'));
    nameDiv.appendChild(fullNameTxt);
    nameDiv.appendChild(fullName);
    var emailTxt = document.createElement('p');
    emailTxt.appendChild(document.createTextNode('Email address'));
    emailDiv.appendChild(emailTxt);
    emailDiv.appendChild(email);
    var submit = document.createElement('input');
    submit.type = 'button';
    submit.id = 'submit';
    //submit.setAttribute("onclick","insertAppointment($('theDateTime'),$('email'),$('fullName'))");
    submit.value = 'submit';
    var notifyDiv = document.createElement('div');
    notifyDiv.className = 'notifyDiv';
    var notify = document.createElement('input');
    notify.type = 'checkbox';
    var notifyTxt = document.createElement('p');
    notifyTxt.appendChild(document.createTextNode('send me notification the day before.'));
    notifyDiv.appendChild(notify);
    notifyDiv.appendChild(notifyTxt);
    inpts.appendChild(nameDiv);
    inpts.appendChild(emailDiv);
    inpts.appendChild(notifyDiv);
    inpts.appendChild(submit);
//    inpts.style.display = 'none';
//    inpts.style.overflow = 'hidden';
//    inpts.style.height = '125px';
    btns.appendChild(schedule);
    nextPhase.appendChild(btnUD);
    //btns.appendChild(warrning);
    //btns.appendChild(exp);
    appointmentCont.appendChild(innerCont);
    if(IsLoggedIn === 'False')
    {
        btns.className = 'confirmBtnHide';
    }
    else
    {
        btns.className = 'confirmBtn';
    }
    //appointmentCont.appendChild(btns);// confirmation button after login
    //appointmentCont.appendChild(nextPhase);// next phase to user details fillup
    
    //appointmentCont.appendChild(inpts);
//    if($('innerCont'))
//        $('innerCont').innerHTML = appointmentCont.innerHTML;//innerCont.innerHTML;
//    else
        $('preDisplay').innerHTML = appointmentCont.innerHTML;
        
    Fat.fade_element('innerCont',60,1000);
    setUserDetails(); //set the selected DT into hidden inputs
}

function setUserDetails() {
    var thedate = $('theDateTime').getAttribute('dt');
    var s_time = $('theDateTime').getAttribute('s_time');
    var e_time = $('theDateTime').getAttribute('e_time');
//    var bName = $('businessTitle').innerHTML;
//    if ($('ddlServices').selectedIndex > -1)
//    var sName = $('ddlServices').options[$('ddlServices').selectedIndex].text;
    strStartTime = thedate + " " + s_time;
    strEndTime = thedate + " " + e_time;
    if ($('inptTimes')) {
        var timesInpt = $('inptTimes').getElementsByTagName('input');
        timesInpt[0].value = strStartTime;
        timesInpt[1].value = strEndTime;
    }
//    if ($('<%=sTime.ClientID %>'))
//        $('<%=sTime.ClientID %>').value = strStartTime;
//    if ($('<%=eTime.ClientID %>'))
//        $('<%=eTime.ClientID %>').value = strEndTime;
    
    //                                    location.href = appPath + "/Pages/C/ClientDetails.aspx?bName=" + bName + "&sName=" + sName + "&s_time=" + strStartTime +
    //    "&e_time=" + strEndTime + "&sid=" + pageParams.ServiceID.toString();
}

function insertAppointment()
{//debugger

    var thedate = $('theDateTime').getAttribute('dt');
    var s_time = $('theDateTime').getAttribute('s_time');
    var e_time = $('theDateTime').getAttribute('e_time');
    strStartTime = "'" + thedate + " " + s_time + "'";
    strEndTime = "'" + thedate + " " + e_time + "'";
    var params = new Array();
    params.push(parseInt(pageParams.ServiceID,10));
    params.push(strStartTime);
    params.push(strEndTime);
//    params.push(clientData.SchedulyUserInfo.userID);
//    params.push(null);//comments
//    params.push(4);//statusID
    jsonObj.asyncWithCallback('jsonHandler','setNewAppointment',params,'callbackSetNewAppointment');

}
function callbackSetNewAppointment(response)
{//debugger
    if(!response)
    {
        staticMessageBox.show('There was some sort of a problem with your reservation, please try again later.'+
                                stillInBetaMsg()
                            ,'error',$('loginMsg'),false);
    }
    else if(response.result!='')
    {
        location.href = appPath + '/pages/c/VoucherPage.aspx?appID=' + response.result.split(';')[0] + 
        '&pid=' + response.result.split(';')[2];
    }
    else
    {
        staticMessageBox.show('There was some sort of a problem with your reservation, please try again later.'+
                                stillInBetaMsg()
                            ,'error',$('loginMsg'),false);
    }
}
//Yahoo calendar
var call;
var mySelectHandler = function(type, args, obj) {

    var selected = args[0];
    if (this._toDate(selected[0])) {
        $('target').innerHTML = loadLoaderIMG();
        removeMsg();
        $('theDate').innerHTML = this._toDate(selected[0]).toStringFullDate(); //toDateString();
        if ($('newApp_theDate'))
            $('newApp_theDate').innerHTML = $('theDate').innerHTML;
        if (this._toDate(selected[0]).compareDate(new Date()) < 0) {
            $('target').innerHTML = '';
            //userMsgDisplayer('noAvailable');
            return;
        }
        var params = new Array();
        //params.push(29);
        var theDate = this._toDate(selected[0]);
        params.push(parseInt($('hidSID').value, 10));
        params.push(parseInt($('hidBID').value, 10));
        params.push("'" + theDate.toStringMMDDYYYY() + "'"); //debugger
        params.push(new Date().getTimezoneOffset());
        params.push(false); //isMonthChanged - to know if to check for available days in this month
        var result = jsonObj.syncReturnValue('jsonHandler', 'getAvailableAppointments', params);
        //debugger
        var arrResult = new Array();
        if (result != '') {
            //result = eval('(' + result + ')');
            result = MassiveParserJSON(result);
            eee = result[0];
            bookedDays = result[1];
        }

        arrResult.push(eee);
        this.data = arrResult;
        if (eee == '' || eee.ListOfDays.length == 0) {
            $('target').innerHTML = noAvailable;
            //            userMsgDisplayer('noAvailable');
            //$('targetmsg').style.display = '';

        }
        else {
            //            $('targetmsg').innerHTML = '';
            //            $('targetmsg').style.display = 'none';
            $('target').innerHTML = '';
            setRepeater(this.data); //[0].AvailableAppointments);

        }

    }
};
var monthChanged = function(type, args, obj) {
    var theDate = new Date();
    theDate.setDate(obj.cellDates[10][2]);
    theDate.setMonth(obj.cellDates[10][1] - 1);
    theDate.setFullYear(obj.cellDates[10][0]);
    removeMsg();


    $('theDate').innerHTML = theDate.toStringFullDate();
    if ($('newApp_theDate'))
        $('newApp_theDate').innerHTML = $('theDate').innerHTML;
    var fnRender = function(workingDate, cell) {
        cell.innerHTML = "<font color='#cccccc'>" + this.buildDayLabel(workingDate) + "</font>";
        return YAHOO.widget.Calendar.STOP_RENDER;
    };
    var sDates = '';
    if (theDate.compareDate(new Date()) < 0 && theDate.getMonth() != new Date().getMonth()) {
        var thePreDate = new Date();
        thePreDate.setDate(1);
        thePreDate.setMonth(obj.cellDates[10][1] - 1);
        thePreDate.setFullYear(obj.cellDates[10][0]);
        $('target').innerHTML = '';
        $('theDate').innerHTML = thePreDate.toStringFullDate();
        if ($('newApp_theDate'))
            $('newApp_theDate').innerHTML = $('theDate').innerHTML;
        sDates = setHistoryDates(1, obj.monthDays + 1, theDate);
        this.addRenderer(sDates, fnRender);
        this.render();
        return;
    }

    if (theDate.getMonth() == new Date().getMonth()) {
        $('target').innerHTML = '';
        sDates = setHistoryDates(1, obj.today.getDate() + 1, theDate);

    }

    var params = new Array();
    params.push(parseInt($('hidSID').value, 10));
    params.push(parseInt($('hidBID').value, 10));
    params.push("'" + theDate.toStringMMDDYYYY() + "'"); //debugger
    params.push(new Date().getTimezoneOffset());
    params.push(true); //isMonthChanged - to know if to check for available days in this month
    var result = jsonObj.syncReturnValue('jsonHandler', 'getAvailableAppointments', params);
    //debugger;
    var arrResult = new Array();

    if (result != '') {
        //result = eval('(' + result + ')');
        result = MassiveParserJSON(result);
        eee = result[0];
        bookedDays = result[1];
    }

    arrResult.push(eee);
    this.data = arrResult;
    if (eee == '' || eee.ListOfDays.length == 0) {
        $('target').innerHTML = noAvailable;
    }
    else {
        setRepeater(this.data);
    }

    sDates = sDates + setBookedDates(bookedDays);

    this.addRenderer(sDates, fnRender);

    this.render();
    //call.render(); 
};
function init(obj,displayDate) { 
//To know if we past to the next month
//var arrDates = call.getSelectedDates(); 
    if(!displayDate)
        displayDate = new Date().toStringMMDDYYYY();

    call = new YAHOO.widget.Calendar("call", "callContainer", { selected: displayDate });
    call.cfg.setProperty("WEEKDAYS_SHORT", [Resources.daysShort_1, Resources.daysShort_2, Resources.daysShort_3, Resources.daysShort_4, Resources.daysShort_5, Resources.daysShort_6, Resources.daysShort_7]);
    call.cfg.setProperty("MONTHS_LONG", [Resources.months_1, Resources.months_2, Resources.months_3, Resources.months_4, Resources.months_5, Resources.months_6, Resources.months_7, Resources.months_8, Resources.months_9, Resources.months_10, Resources.months_11, Resources.months_12]);
   
   var sDates = '';
   if(call.today.getDate() > 1)
    sDates = setHistoryDates(1,call.today.getDate()+1,call.today);
   
   sDates = sDates + setBookedDates(obj);//"12/12/2007,12/19/2007,12/23/2007";
   //debugger
   var fnRender = function(workingDate, cell) {//debugger
   cell.innerHTML = "<font color='#cccccc'>" + this.buildDayLabel(workingDate) + "</font>";
   return YAHOO.widget.Calendar.STOP_RENDER; 
}
    
    call.selectEvent.subscribe(mySelectHandler,call,true);
    call.changePageEvent.subscribe(monthChanged,call,true);
    call.addRenderer(sDates,fnRender);
    call.render(); 
   
   
} 
function setHistoryDates(startDay,endDay,dateObj)
{
    var bookedDates = new Array();
    
    var tempDate = dateObj;//new Date();
    
//        tempDate.setMonth(month);
//        tempDate.setDate(1);
//        while(tempDate.getMonth() == month)
//        {
//            bookedDates.push(tempDate.toStringMMDDYYYY());
//            tempDate.setDate(tempDate.getDate()+1);
//        }
        for(i=startDay;i<endDay;i++)
        {
            tempDate.setDate(i);
            bookedDates.push(tempDate.toStringMMDDYYYY());
            
        }
        return bookedDates.join(',');
    
}
function setBookedDates(obj,month)
{
    if(!obj)return "";
    var bookedDates = new Array();
    
    
    
    for(i=0;i<obj.length;i++)
    {
        if (obj[i].FreeSlots <= 0) //debugger;
            bookedDates.push(obj[i].Date.toStringMMDDYYYY());
    }
    return bookedDates.join(',');
}
//end Yahoo Calendar

function callbackGetUserInfo(response)
{
    if(response)
    {
        if(response.result != '' && response.result != '{}' && response.result != '[]')
        {
            clientData = eval('(' + response.result + ')');
        }
    }
}
var GLOBAL_SERVICE_ID = -1;
var bookedDays = null;
var pageViews = -1;



function start(requestedDate)
{
//debugger
appointMgr = new MyAppointmentsMgr();
//    var ddd = jsonObj.syncReturnValue('jsonHandler','getSelectedServicesesByUser','');
//    ddd = eval('(' + ddd + ')');
var params = new Array();
var theDate = new Date();
if(requestedDate)
 theDate = requestedDate;   
  
params.push(parseInt($('hidSID').value,10));
params.push(parseInt($('hidBID').value,10));
params.push("'" + theDate.toStringMMDDYYYY()+ "'");
params.push(new Date().getTimezoneOffset());
params.push(true);//isMonthChanged - to know if to check for available days in this month
var result = jsonObj.syncReturnValue('jsonHandler','getAvailableAppointments',params);
//debugger;
var arrResult = new Array();

if(result!='')
{
    //result = eval('(' + result + ')');
    result = MassiveParserJSON(result);
    eee = result[0];
    bookedDays = result[1];
}

init(bookedDays);//Yahoo calendar init

arrResult.push(eee);
this.data = arrResult;

var addressX;
var addressY;
var zipCodeX;
var zipCodeY;
//debugger;
if(eee.ServiceInfo[0])
{
    GLOBAL_SERVICE_ID = eee.ServiceInfo[0].ServiceID;
    getOtherServicesOfTheBusiness(GLOBAL_SERVICE_ID);
    addressX = eee.ServiceInfo[0].AddressX;
    addressY = eee.ServiceInfo[0].AddressY;
    zipCodeX = eee.ServiceInfo[0].ZipCodeX;
    zipCodeY = eee.ServiceInfo[0].ZipCodeY;
    if ($('GMT')) {
        var GMT = parseFloat(eee.ServiceInfo[0].GMT)
        if (GMT > 0)
            GMT = "(GMT +" + eee.ServiceInfo[0].GMT +")";
        else
            GMT = "(GMT " + eee.ServiceInfo[0].GMT + ")";
        $('GMT').innerHTML = GMT;
    }
    setDetails();
    
    //document.title = 'Scheduly |' + eee.ServiceInfo[0].ServiceName+ " at " + eee.ServiceInfo[0].BusinessName ;
    
    //if($('contOtherServices').style)
//    $('otherServices').innerHTML = 'All Services at ' + eee.ServiceInfo[0].BusinessName;
    /*AddThis button param*/
    addthis_title  = 'Scheduly |' + eee.ServiceInfo[0].ServiceName+ " at " + eee.ServiceInfo[0].BusinessName;
//    var addThisLocation = $('addThis');
//    var addThisScript = document.createElement('script');
//    addThisScript.type = 'text/javascript';
//    addThisScript.src = 'http://s7.addthis.com/js/addthis_widget.php?v=12';
//    addThisLocation.appendChild(addThisScript);// = '<scr'+'ipt type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12"></sc'+'ript>'
    
}
$('theDate').innerHTML = getSelectedDate().toStringFullDate(); //toDateString();
if ($('newApp_theDate'))
    $('newApp_theDate').innerHTML = $('theDate').innerHTML;
if(eee=='' || eee.ListOfDays.length == 0)
{
    $('target').innerHTML = noAvailable;
}
else
{
//    $('serviceTitle').innerHTML = eee.ListOfDays[0].ServiceName;
//    $('businessTitle').innerHTML = eee.ListOfDays[0].BusinessName;
//    $('servicePrice').innerHTML = eee.ListOfDays[0].Price + " " + '(for ' + eee.ListOfDays[0].Duration +' min)';
//    $('serviceDesc').innerHTML = eee.ListOfDays[0].ServiceDesc.replaceBackQuotes();
//    $('serviceOverlap').innerHTML = "I'm handling with " + 
//        (eee.ListOfDays[0].OverLapNumber>1? eee.ListOfDays[0].OverLapNumber + 
//        " clients ":eee.ListOfDays[0].OverLapNumber + " client ") + "at a time.";
//    document.title = 'Scheduly | ' + eee.ListOfDays[0].ServiceName+ " at " + eee.ListOfDays[0].BusinessName ;


//    
    setRepeater(this.data);
}
    if($('map_canvas'))
    load(addressX,addressY,zipCodeX,zipCodeY);
} 
function setDetails()
{
    $('hidSID').value = eee.ServiceInfo[0].ServiceID;
    pageParams.ServiceID = eee.ServiceInfo[0].ServiceID;
    if($('serviceTitle'))
        $('serviceTitle').innerHTML = eee.ServiceInfo[0].ServiceName;
    if($('businessTitle'))
        $('businessTitle').innerHTML = eee.ServiceInfo[0].BusinessName;
    if($('servicePrice') && eee.ServiceInfo[0].Price > -1)
        $('servicePrice').innerHTML = "<div><font>" + Resources.GeneralPrice + ":</font> <span>" + eee.ServiceInfo[0].Price + " " + "("+Resources.For+ " " + eee.ServiceInfo[0].Duration + " "+Resources.min + ")</span></div>";
    else if($('servicePrice'))
    {
        $('servicePrice').innerHTML = "<div><font>" + Resources.GeneralServiceDuration + ":</font> <span>" + eee.ServiceInfo[0].Duration + " " + Resources.min + "</span></div>";
    }
    if($('serviceDesc'))
        $('serviceDesc').innerHTML = eee.ServiceInfo[0].ServiceDesc.replaceBackQuotes().replace(new RegExp("LINE_BREAK", "g"), "<br />").replace(new RegExp("PRESENTAGE_S", "g"), "%");
    if($('serviceOverlap'))
    {
        $('serviceOverlap').innerHTML = "<div><font>" + Resources.businessPage_Overlap1 + " " + 
        (eee.ServiceInfo[0].OverlapNum>1? eee.ServiceInfo[0].OverlapNum +
        " " + Resources.clients + " " : eee.ServiceInfo[0].OverlapNum + " " + Resources.client + " ") + Resources.businessPage_Overlap2 + "</font></div>";
    }
    if($('address'))
    {
        if(eee.ServiceInfo[0].BusinessAddress)
        {
            $('address').innerHTML = eee.ServiceInfo[0].BusinessAddress;
        }
        else
        {
            $('address').innerHTML = '';
        }
    }
    //debugger
    if($('phone'))
    {
        $('phone').innerHTML = "<div><font>" + Resources.GeneralPhoneNumber + ":</font> <span>" + (eee.ServiceInfo[0].Phone ? eee.ServiceInfo[0].Phone : "") + "</span></div>";
    }
    if($('fax'))
    {
        $('fax').innerHTML = "<div><font>"+Resources.Fax+":</font> <span>" + (eee.ServiceInfo[0].Fax ? eee.ServiceInfo[0].Fax : "") + "</span></div>";
    }
    var bpURL;
    if($('website')) {
        if (eee.ServiceInfo[0].WebSite) {
            bpURL = (eee.ServiceInfo[0].WebSite.indexOf("http") < 0 ? "http:" + "//" + eee.ServiceInfo[0].WebSite : eee.ServiceInfo[0].WebSite);
            $('website').innerHTML = "<div><font>" + Resources.GeneralWebSite + ":</font> <span>" + (eee.ServiceInfo[0].WebSite ? "<a href='" + bpURL + "'>" + bpURL + "</a>" : "") + "</span></div>";
        }
    }
    if($('busEmail'))
    {
        $('busEmail').innerHTML = "<div><font>" + Resources.Email + ":</font> <span>" + (eee.ServiceInfo[0].Email ? "<a href='mailTo:" + eee.ServiceInfo[0].Email + "'>" + eee.ServiceInfo[0].Email + "</a>" : "") + "</span></div>";
    }
    if($('mobile'))
    {
        $('mobile').innerHTML = "<div><font>" + Resources.businessPage_Mobile + ":</font> <span>" + (eee.ServiceInfo[0].Mobile ? eee.ServiceInfo[0].Mobile : "") + "</span></div>";
    }
    if($('providerName')) {
        $('providerName').innerHTML = "<div><font>" + Resources.businessPage_ServiceProviderName + ":</font> <span>" + (eee.ServiceInfo[0].ProviderName ? eee.ServiceInfo[0].ProviderName : "") + "</span></div>";
        if($('manageBy'))
            $('manageBy').innerHTML = Resources.widget_ManagedBy + " " + (eee.ServiceInfo[0].ManagerName ? eee.ServiceInfo[0].ManagerName : "");
    }
    if($('appointmentsCount'))
    {
        $('appointmentsCount').innerHTML = (eee.ServiceInfo[0].AppointmentsCount?eee.ServiceInfo[0].AppointmentsCount:"0")
    }
    if($('photo'))
    {
        //alert(eee.ServiceInfo[0].ImageUrl);
        $('photo').innerHTML = "<img src='" + imagesUrl +(eee.ServiceInfo[0].ImageUrl?eee.ServiceInfo[0].ImageUrl:"defaultMemberImg.jpg")+"'/>"
        Rounded("div#minipicsBusiness li","#fff","#d7e2f5");
    }
}
function setRepeater(data,target)
{//debugger
    this.pageNum = 1;
    //obtaining the template
    var strTemplate = $("template1").value;
    //obtaining the target element 
    var oTargetRow
    if(target)
        oTargetRow = target;
    else
        oTargetRow = $("target");
    var oTimeTemplate = null;//$('template2').value;
    var oMapping = {
        SERVICE_TITLE: function(item) { return item.ListOfDays[0].ServiceName }
                        , BUSINESS_TITLE: function(item) { return item.ListOfDays[0].BusinessName }
                        , DATE: function(item, itemParent) {
                            return getSelectedDate().toDateString();
                        }
                        , TIME: function(item) { //var sss = new Date();sss.toDateString()
                            //debugger
                            if (item.ListOfDays)
                                this.dataItem = item.ListOfDays; //AvailableAppointments;
                            else
                                return '';
                            //obtaining the template
                            var strTemplate1 = $('template2').value; //item.innerTemplate;
                            //defining mapping:
                            var oMapping1 = {
                                SERVICE_TITLE: function(item) { return item.ServiceName; }
                                                                                , SERVICE_ID: function(item) { return item.ServiceID; }
                                                                                , BUSINESS_TITLE: function(item) { return item.ServiceName; }
                                                                                , BUSINESS_ID: function(item) { return item.BusinessID; }
                                                                                , GMT: function(item) { return item.StartTime.toStringHHmm() + " - " + item.EndTime.toStringHHmm(); }
                                                                                , TIME_STAMP: function(item) {  return item.StartTime.toStringHHmm().allTrim() + "-" + item.EndTime.toStringHHmm().allTrim(); }
                                                                                , DATE: function(item) { return getSelectedDate().toDateString(); }
                                                                                , SHORT_DT: function(item) { return getSelectedDate().toStringMMDDYYYY(); }
                                                                                , settings: { pageRefer: "NewAppPhase3"}//the 'pageRefer' property is helping to save the selected rows see 'setCheckBoxAsPreDisplay' function
                            };

                            this.repeater = new TC.Controls.Repeater(strTemplate1);
                            this.repeater.onItemDataBound = function(item, itemParent) {//debugger toStringHHmm
                                //item.template = setCheckBoxAsPreDisplay(item);
                                //                                                                                                                if(isWinLoad)
                                //                                                                                                                {
                                //                                                                                                                    item.mapping.TIME_STAMP = item.StartTime.toStringHHmm() + " - " + item.EndTime.toStringHHmm();
                                //                                                                                                                    
                                //                                                                                                                }
                            };
                            var theTimes = '';
                            if (!isNullOrUndefined(this.dataItem)) {
                                this.repeater.dataBind(oMapping1, this.dataItem, item);
                                theTimes = this.repeater.content.toString(); //Returning an HTML as string (the render() returns HTML and dataBind() returns HTML string)
                            }
                            return theTimes;
                        }


    };
    //var oParseTags =	{ serviceTitle		: "ServiceName" }; 
    //appointMgr.funcOnDataBind = function(dataSource){debugger;var i = 0;};
    appointMgr.init(strTemplate,oTimeTemplate,data,oTargetRow,this.pageNum,$('tdPageNums'),1,oMapping);
    appointMgr.execute();
    //setPagingBar(appointMgr);
    
}
var qsParams = getQueryStringParams();
function getOtherServicesOfTheBusiness(serviceID)
{
    
if(!$('ddlServices'))return;
    var bID = -1;
    var sID = serviceID;//-1;
    
    if(!isNullOrUndefined(qsParams['bID']))
        bID = parseInt(qsParams['bID'],10);
//    if(!isNullOrUndefined(qsParams['sID']))
//        sID = parseInt(qsParams['sID'],10);
    var params = new Array();
    params.push(bID);
    params.push(sID);
    jsonObj.asyncWithCallback('jsonHandler','getBusinessServicesInfo',params,callbackgetBusinessServices);

}

function callbackgetBusinessServices(response)
{
    if(!response)return;
    if(response.result!='' && response.result!='[]' && response.result!='{}')
    {
        var data = eval('('+response.result+')');
        if(data.length > 1)
        {
            var counter = 0;
            for(i=0;i<data.length;i++)
            {
                if(i > 0 && data[i].Name != data[i-1].Name)
                {
                    $('ddlServices').options[counter] = new Option(data[i].Name,data[i].ServiceID); 
                    if(!isNullOrUndefined(qsParams['sID']) && parseInt(qsParams['sID'],10) == data[i].ServiceID)
                    {
                        $('ddlServices').options[counter].selected = true;
                    }
                    if(!isNullOrUndefined(qsParams['sID']) && $('hidSID').value!= qsParams['sID'] && data[i].ServiceID == $('hidSID').value)
                    {
                        $('ddlServices').options[counter].selected = true;
                    }
                    if(!isNullOrUndefined(qsParams['bID']) && data[i].ServiceID == $('hidSID').value)
                    {
                        $('ddlServices').options[counter].selected = true;
                    }
                    counter++;
                }
                else if(i == 0)
                {
                    $('ddlServices').options[counter] = new Option(data[i].Name,data[i].ServiceID);
                    counter++;
                }
            }
            $('cont_ddlServices').style.display = '';
            $('serviceTitle').style.display = 'none';
        }
        else
        {
            $('cont_ddlServices').style.display = 'none';
            $('serviceTitle').style.display = '';
        }
    }
}
function goToServicePage(id)
{
    location.href = appPath+'/pages/c/businessPage.aspx?sID=' + $(id).options[$(id).selectedIndex].value;
}
function getServiceAvailability(obj)
{
    $('hidSID').value = obj.options[obj.selectedIndex].value;// serviceID
    start();
}
//function setServicesRepeater(data,target)
//{
//    //debugger
//    appointMgr1 = new MyAppointmentsMgr();
//    this.pageNum = 1;
//    //obtaining the template
//    var strTemplate = $("servicesTemplate").value;
//    //obtaining the target element 
//    var  oTargetRow = target;
//    
//    var oTimeTemplate = null;//$('template2').value;
//    var oMapping = {
//                        SERVICE_NAME    :  "Name"
//                        ,SERVICE_ID     :  "ServiceID"
//                        ,HREF_LINK      : ""
//                        ,LINK_CLASS     : ""
//                    
//                   };
//    appointMgr1.funcOnItemDataBound = function(item){
//                                                        if(item.dataItem.ServiceID == GLOBAL_SERVICE_ID)
//                                                        {
//                                                            item.mapping.HREF_LINK = '';
//                                                            item.mapping.LINK_CLASS = 'class="nonAnchor"';
//                                                        }
//                                                        else
//                                                        {
//                                                            item.mapping.HREF_LINK = 'href="<%=appPath %>/pages/c/businesspage.aspx?sID='+item.dataItem.ServiceID+'"';
//                                                        }
//                                                            
//                                                    }
//    appointMgr1.init(strTemplate,oTimeTemplate,data,oTargetRow,this.pageNum,$('tdPageNums'),data.length,oMapping);
//    return appointMgr1.execute();
//    
//    
//}

function userMsgDisplayer(type,obj,txt)
{
    switch(type)
    {
        case 'noAvailable':
            staticMessageBox.show('Sorry, there are no available appointments for this date.','note',$('targetmsg'),false);
        break;
        case 'history':
            staticMessageBox.show('You\'re watching history.','note',$('msg'),true);
        break;
        case 'registered':
            staticMessageBox.show('Thanks for registering to Scheduly.;An E-mail containing your account details is on its way.','success',obj,true);
        break;
        case 'login':
            staticMessageBox.show('You were logged in successfuly, proceed with your reservation','success',obj,true);
        break;
        case 'notLogin':
            staticMessageBox.show(Resources.alert_InvalidEmailOrPassword, 'error', obj, true);
        break;
        case 'successSchedule':
            staticMessageBox.show(txt,'success',obj,true);
        break;
        default:
        break;
    }
}

/*
For the Widget.aspx only
*/
function cancelLoginWidget(id) {
//    alert(111);
//    alert($('cont_ddlServices').options[0].text);
//    if ($('cont_ddlServices')) {
//        
//        if (!isNullOrUndefined($('cont_ddlServices').options[0].text))
//        {
//            $('cont_ddlServices').style.display = ''; //for IE6
//        }
//    
//     }
    
if ($('selectBlock'))
    $('selectBlock').style.display = 'none';
if ($(id))
    $(id).style.top = '250px';
    if ($('err_email'))
    $('err_email').style.visibility = 'hidden';
if ($('err_password'))
    $('err_password').style.visibility = 'hidden';
if ($('errorLogin'))
    $('errorLogin').style.display = 'none';
if ($('errorReservation'))
    $('errorReservation').style.display = 'none';
if ($('successMsg'))
    $('successMsg').style.display = 'none';
if ($('theCal'))
    $('theCal').style.display = '';
}
function setWidgetAppointment(id) {
    if ($('innerselection')) {
        if ($('innerselection').style.display == 'none')
            $('innerselection').setAttribute('style', 'display=;');
    }
    
    var lastShow = YAHOO.util.Dom.getElementsByClassName('selected', 'a');
    lastShow[0]?lastShow[0].className = 'none':null;
    $(id).className = 'selected';

    $('theCal').style.display = 'none';
    //aRow_TIME_STAMP-SHORT_DT-SERVICE_ID
    var dt = id.split('_')[1];
    dt = dt.split('-');
    var showDT = getSelectedDate().toStringFullDate();
    var showTime = dt[0] + "-" + dt[1];
    
//    var divTime = document.createElement('div');
//    divTime.style.width = "100px";
//    divTime.setAttribute = ("style","width:100px;margin:20px auto") 
//    divTime.appendChild(document.createTextNode(showTime));
    var appointmentCont = document.createElement('div');
    appointmentCont.id = 'appointmentCont';
    var innerCont = document.createElement('div');
    innerCont.id = 'innerCont';
    innerCont.className = 'innerContBP';
    innerCont.style.background = "#fff";
    var breakline = document.createElement('br');
    var txt = document.createElement('div');
    var font = document.createElement('font');
    font.style.color = '#cc4b00';
    if ($('ddlServices').selectedIndex > -1)
        font.appendChild(document.createTextNode($('ddlServices').options[$('ddlServices').selectedIndex].text + ' ' + Resources.at + ' ' + $('businessTitle').innerHTML))
    else
        font.appendChild(document.createTextNode($('serviceTitle').innerHTML + ' ' + Resources.at + ' ' + $('businessTitle').innerHTML))
    txt.appendChild(font);
    //txt.appendChild(document.createElement('br'));
    //txt.appendChild(document.createTextNode(memberFullName));
    txt.appendChild(document.createElement('br'));
    txt.appendChild(document.createTextNode(showDT));//getSelectedDate().toDateString()));
    txt.appendChild(document.createElement('br'));
    txt.appendChild(document.createTextNode(showTime));
    txt.className = 'appointHour';
    txt.id = 'theDateTime';
    setDateTimeAttribute(txt,dt[0],dt[1]);
    innerCont.appendChild(txt);
    var btns = document.createElement('div');
    btns.id = 'confirmBtn';
//    var cancel = document.createElement('a');
//    cancel.href = 'javascript://';
//    cancel.innerHTML = 'cancel';
    var schedule = document.createElement('input');//('a');
    schedule.type = 'button';
    //schedule.href = '#';
    //schedule.innerHTML = 'grab it!';
    var warrning = document.createElement('p');
    warrning.appendChild(document.createTextNode(Resources.GrabItHelp));//'(clicking on the \'Grab It!\' button will set you appointment with this business and notification will be send to you both.)'));
    warrning.className = 'grabItWarrning';
    schedule.value = Resources.GrabIt;
    schedule.setAttribute("onclick","insertAppointmentWidget()");
    //  btns.appendChild(cancel);
    //Inputs: full name and email
    var inpts = document.createElement('div');
    inpts.className = 'confirmationInputs';
    inpts.id = 'clientDetails';
    var nameDiv = document.createElement('div');
    var emailDiv = document.createElement('div');
    var fullName = document.createElement('input');
    fullName.type = 'text';
    fullName.id = 'fullName';
    var email = document.createElement('input');
    email.type = 'text';
    email.id = 'email';
    var fullNameTxt = document.createElement('p');
    fullNameTxt.appendChild(document.createTextNode('Full Name'));
    nameDiv.appendChild(fullNameTxt);
    nameDiv.appendChild(fullName);
    var emailTxt = document.createElement('p');
    emailTxt.appendChild(document.createTextNode('Email address'));
    emailDiv.appendChild(emailTxt);
    emailDiv.appendChild(email);
    var submit = document.createElement('input');
    submit.type = 'button';
    submit.id = 'submit';
    //submit.setAttribute("onclick","insertAppointment($('theDateTime'),$('email'),$('fullName'))");
    submit.value = 'submit';
    var notifyDiv = document.createElement('div');
    notifyDiv.className = 'notifyDiv';
    var notify = document.createElement('input');
    notify.type = 'checkbox';
    var notifyTxt = document.createElement('p');
    notifyTxt.appendChild(document.createTextNode('send me notification the day before.'));
    notifyDiv.appendChild(notify);
    notifyDiv.appendChild(notifyTxt);
    inpts.appendChild(nameDiv);
    inpts.appendChild(emailDiv);
    inpts.appendChild(notifyDiv);
    inpts.appendChild(submit);
//    inpts.style.display = 'none';
//    inpts.style.overflow = 'hidden';
//    inpts.style.height = '125px';
    btns.appendChild(schedule);
    btns.appendChild(warrning);
    appointmentCont.appendChild(innerCont);
//    if(IsLoggedIn == 'False')
//    {
        btns.className = 'confirmBtnHide';
//    }
//    else
//    {
//        btns.className = 'confirmBtn';
//    }
    //alert(btns.className);
    appointmentCont.appendChild(btns);
    $('cont_ddlServices').style.display = 'none'; //for IE6
    //alert($('innerCont'))
    if($('innerCont'))
        $('innerCont').innerHTML = innerCont.innerHTML;
    else
        $('preDisplay').innerHTML = appointmentCont.innerHTML;
    
    
    $('selectBlock').style.position = 'absolute';
    $('selectBlock').style.top = '0';
    $('selectBlock').style.left = '0';
    $('selectBlock').style.display = '';
    Fat.fade_element('innerCont',60,1000);
    Rounded("div#innerCont", secondPaletteColor, "#fff");
    setUserDetails(); 
}
var clientData = new Object();
function loginWidget(id)
{
    var params = checkFields(id);
    if(params!=null)
    {
        params.push(new Date().getTimezoneOffset());
        jsonObj.asyncWithCallback('jsonHandler','LoginReturnUserInfo',params,'callbackLoginWidget');
    }
}
function callbackLoginWidget(response)
{
    if(response)
    {
        if(response.result!='' && response.result!='{}' && response.result!='[]')
        {
            clientData = eval('(' + response.result+')');
            isLoggedIn = "True";
            FullName = clientData.SchedulyUserInfo.firstName + ' ' + clientData.SchedulyUserInfo.lastName;
            if($('confirmBtn'))
                $('confirmBtn').className = 'confirmBtn';
            $('loginDetails').style.display = 'none';
            if ($('cont_login'))
            $('cont_login').style.display = 'none';
            $('errorLogin').style.display = 'none';
        }
        else
        {
            $('errorLogin').style.display = '';
        }
    }
}
function insertAppointmentWidget()
{
    $('appDetails').innerHTML = $('theDateTime').innerHTML;
    var thedate = $('theDateTime').getAttribute('dt');
    var s_time = $('theDateTime').getAttribute('s_time');
    var e_time = $('theDateTime').getAttribute('e_time');
    strStartTime = "'" + thedate + " " + s_time + "'";
    strEndTime = "'" + thedate + " " + e_time + "'";
    var params = new Array();
    
    params.push(parseInt(pageParams.ServiceID,10));
    params.push(strStartTime);
    params.push(strEndTime);
    jsonObj.asyncWithCallback('jsonHandler','setNewAppointment',params,'callbackSetNewAppointmentWidget');

}
function callbackSetNewAppointmentWidget(response)
{
    if(!response)
    {
        staticMessageBox.show('There was some sort of a problem with your reservation, please try again later.'+
                                stillInBetaMsg()
                            ,'error',$('preDisplay'),true);
    }
    else if(response.result && response.result !='')
    {
        var data = response.result.split(';');
        var appointmentID = data[0];
        var permalink = data[2];

        var link = '<a id="voucherLink" target="_top" href="' + appPath + '/pages/c/VoucherPage.aspx?appID=' + appointmentID + '&pid=' + permalink + '">' + Resources.voucherPage + '</a>';
        $('voucherLink').innerHTML = link;
        $('successMsg').style.display = '';
        start();
    }
    else
    {
        $('errorReservation').style.display = '';

    }
}
/*
End of the Widgwt.aspx
*/
function gotoHomepage()
{
    location.href = appPath + '/home.aspx';
}