var trainingDateID = [];
var trainingDates = [];
var startDates = [];
var endDates = [];
var trainingDateAndTime = [];
var trainingLocation = [];
var currDateTime = new Date();
var currDate = currDateTime.getMonth() + 1 + "/" + currDateTime.getDate() +"/" + currDateTime.getFullYear();
var currMonth = currDateTime.getMonth() +1;
var currYear = currDateTime.getFullYear();
var currTrainingID = null;
var currGroupID = null;
var servicePath = "./trainingWS.asmx/";

var monthNames = ["January","February","March","April","May","June","July","August","September", "October","November","December"]
var monthNamesShort = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep", "Oct","Nov","Dec"]

var registerClicked = false;
img1 = new Image(); 
img1.src = "images/body2.gif";
img2 = new Image();
img2.src = "images/menu/sec_career.jpg";
img3 = new Image();
img3.src = "images/menu/sec_clients.jpg";
img4 = new Image();
img4.src = "images/menu/sec_company.jpg";
img5 = new Image();
img5.src = "images/menu/sec_contactus.jpg";
img6 = new Image();
img6.src = "images/menu/sec_gsa.jpg";
img7 = new Image();
img7.src = "images/menu/sec_news.jpg";
img8 = new Image();
img8.src = "images/menu/sec_services.jpg";
img9 = new Image();
img9.src = "images/menu/sec_training.jpg";
img10 = new Image();
img10.src = "images/index_BG.gif";

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  if(selObj.options[selObj.selectedIndex].value != -1){
    eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  }
  if (restore) selObj.selectedIndex=0;
}

function loadTrainingCoursePage()
{
     $(document).ready(function() {
		$("#calendar_Training").datepicker({
            minDate:currDateTime,
            numberOfMonths: 3,
            beforeShowDay: markSpecialDays, 
            onChangeMonthYear: monthYearChanged,
            onSelect: daySelected
        });
		create_TrainingDates_Dialog();
		$("#btnSelectDate").bind("click",function() { 
		    selectSeat();
		}); 
 });
}


function loadRegisterPage()
{
    setRegisterTraining_Events();
    create_Legal_Dialog();
    //on register click:
    $("#btnValThenReg").bind("click",function() { 
            registerClicked = true;
            if(validateRegisterScreen()){
                show_Legal_Dialog();
	        }	    
	}); 

}

// **************************************************************************************
// Training Course Page 
// **************************************************************************************


function daySelected(selDate)
{
    if(selDate.substr(0,1) == '0'){
        selDate = selDate.substr(1,selDate.length-1);
    }
    if(selDate.substr(1,1) == '/'){
        if(selDate.substr(2,1) == '0'){
            selDate = selDate.substr(0,2) + selDate.substr(3,selDate.length-1);
        }
    }
    else{
        if(selDate.substr(3,1) == '0'){
            selDate = selDate.substr(0,3) + selDate.substr(4,selDate.length-1);
        }
    }
    var arrIndex = $.inArray(selDate,trainingDates);
    if(arrIndex != -1){
        $("#dialog_SelectedTrainingDate").html(selDate);
        $("#dialog_Location").html(trainingLocation[arrIndex]);
        $("#dialog_TrainingTime").html(getTime(trainingDateAndTime[arrIndex]));
        $("#selectSeat").hide();
        $("#selectSeatImg").hide();
        $("#trainingDate").val(selDate);
        $("#trainingDateID").val(trainingDateID[arrIndex]);        
    }
} 

function getTime(selDate)
{
    var hours = selDate.getHours()
    var minutes = selDate.getMinutes()
    var returnVal;
    if (minutes < 10){
        minutes = "0" + minutes
    }
    if(hours > 13){
        hours -=12;
        returnVal = hours + ":" + minutes + " PM";
    } 
    else {
        returnVal = hours + ":" + minutes + " AM";
    }
    return returnVal;

}
function monthYearChanged(yr,month)
{
  $(document).ready(function(){
      currMonth = month;
      currYear = yr;
      show_TrainingDates_Dialog(currTrainingID, currGroupID);
  });
}

//###########################################################################################################
//## Dialogs ################################################################################################
//###########################################################################################################

//Request Submitted Dialog
function create_TrainingDates_Dialog()
{
    
   $(document).ready(function(){
        $("#dialog_TrainingDetail").dialog({ 
            autoOpen: false,
            buttons: { 
                "Close": function() { 
                        $(this).dialog("close");
                 }
           },
           resizable: true,
           width: 660,
           height: 570,
           maxHeight:800,
           minHeight:570,
           minWidth:660,
           modal: true
           }
         );
   });
}

function show_TrainingDates_Dialog(trainingID, groupID)
{
    if(trainingID != null && groupID != null){
    currTrainingID = trainingID;
    currGroupID = groupID;
    $("#noAvailableDates").hide();
    var startDate = currMonth + "/1" + "/" + currYear;
	$.ajax({
		type: "POST",
		url: servicePath + 'GetTrainingDates',
		data: "{'trainingID':'" +trainingID +"','startDate':'" +startDate +"'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		dataFilter: function (data, type) {
		return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1');
		},
		beforeSend: function(xhr) {
			xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
		},
		success: function(data) {
			$("#trainingDates").empty();
			if(data.length == 0){
                    $("#noAvailableDates").show();
            }
            else{
                addSpecialDays(data);
            }
			$('#dialog_TrainingDetail').show();
            $('#dialog_TrainingDetail').dialog('open');
            $("#dialog_GroupName").html("("+$("#groupName_"+groupID).html() +")");
            $("#dialog_TrainingName").html($("#trainingName_"+trainingID).html());
            $("#dialog_TrainingPrice").html("$"+$("#p_"+trainingID).val());    
            $("#dialog_TrainingDuration").html($("#duration_"+trainingID).val()); 
			
		}
	});
	}
}

//store days in arrays
function addSpecialDays(data) {
	specialDays = [];
	var gCount = 0;
	var hCount = 0;
	for (var i = 0; i < data.length; i++) {
			startDates[hCount] = formatDate(data[i].StartDate, true, true);
			hCount++;
			addClassToMonth(data[i], true);
	}
	
}
	//mark days on calendar using array of days
	function markSpecialDays(date) {
		
		/*var theday = date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
		var isToday = false;
		if (formatDate(new Date(), true, true) == theday) {
			isToday = true;
		}
		if ($.inArray(theday, startDates) != -1) {
			if (isToday) {
				return [true, "generalEvent today"];
			}
			return [true, "generalEvent"];
		}
		//is today, and no holidays or events:
		if (isToday) {
			return [true, "today"];
		}
		else {
			return [true, "normalDay"];
		}*/
		return [false, ""];
	}


function addClassToMonth(item, newClass) {
    
    //month does not exist
    currMonth = item.StartDate.getMonth() +1;
    if($("#month_"+currMonth).length == 0){
        var tableMonth = "<table width='100%' border='0' id='month_"+currMonth +"' class='classTable'><thead><tr><th width='12%'>Start</th><th width='12%'>Time</th><th width='12%'>End</th><th width='12%'>Time</th><th width='20%'>Location</th><th class='buttons' width='10%'>&nbsp;</th></tr></thead><tbody></tbody>";
        $("#trainingDates").append("<div class='headline' style='padding-bottom:4px;padding-top:16px;'>"+monthNames[currMonth-1] +"</div>" +tableMonth);
    }
    var rowText = "<tr id='hover_Class" + item.TrainingDateID + "'><td>" + formatDate(item.StartDate, true, false) + "</td><td>" + formatTime(item.StartTime) + "</td><td>" + formatDate(item.EndDate, true, false) + "</td><td>" + formatTime(item.EndTime) + "</td><td>"+item.Location +"</td>";
    rowText += "<td class='buttons'><a href='#' id='classSelect_" + item.TrainingDateID + "' class='fg-button ui-state-default fg-button-icon-left ui-corner-all' title='Select Class'><span class='ui-icon ui-icon-play' style='display:inline'></span>Select</a>";
                        
    
    //<a href='javascript:void(0)' id='classSelect_" + item.TrainingDateID + "' class='' title='Select Class'>Select</a></td></tr>";

    
    //if new, add row
    if (newClass) {
        //alert(rowText)
        $("#month_"+currMonth +" tbody").append(rowText);
    } //else replace:
    else {
        $("#hover_Class" + item.TrainingDateID).remove();
        $("#month_"+currMonth +" tbody").append(rowText);
        //    $("#hover_Class" + item.TrainingDateID).replaceWith(rowText);
    }
        
    //select class click
    $("#classSelect_" + item.TrainingDateID).click(function() {
        $("#trainingDateID").val(item.TrainingDateID);
        $("#trainingID").val(item.TrainingID);
        $(".btnRegister").click();
        
    });
    
    //admin on hover:
    $("#hover_Class" + item.TrainingDateID).hover(
        function() { $(this).addClass('hover'); },
        function() { $(this).removeClass('hover'); }
    );
}

//Show selected month's events
	function showCurrentMonthEvents(year, month) {
		/*
		$(document).ready(function() {
			var hideDivID = "event_Month_Div" + currentMonth + "_" + currentYear;
			var showDivID = "event_Month_Div";
			showDivID += month + "_" + year;
			currentMonth = month;
			currentYear = year;

			$("#" + hideDivID).slideUp('slow');
			if ($("#" + showDivID).length === 0) {
				if ($("#emptyMonth").is(":hidden")) {
					$("#emptyMonth").slideDown('slow');
				}
			}
			else {
				$("#emptyMonth").slideUp('slow');
				$("#" + showDivID).slideDown('slow');
			}
		});*/
	}




//Show Training Dates Dialog
function show_TrainingDates_DialogOld(trainingID, groupID)
{
  $("#trainingID").val(trainingID);
  $("#noAvailableDates").hide();
  $("#selectSeat").hide();
  $("#selectSeatImg").hide();
  
  $("#dialog_SelectedTrainingDate").html("-None-");
  $("#dialog_Location").html("");
  $("#dialog_TrainingTime").html("");
  $("#trainingDate").val("");
  $("#selecTable").show();
  $("#btnSelectDate").show();
    $.ajax({
            type: "POST",
            url: servicePath + 'GetTrainingDates',
            data: "{'trainingID':'" +trainingID +"','includeStartDate':'true'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            dataFilter: function (data, type) {
            return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1');
            },
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Content-type",
             "application/json; charset=utf-8");
            },
            success: function(data) {
                trainingDates = [];
                for (var i=0; i < data.length; i++){
                    trainingDateID[i] = data[i].TrainingDateID;
                    trainingDates[i] = data[i].TrainingDate.getMonth()+1 +"/" + data[i].TrainingDate.getDate() +"/" + data[i].TrainingDate.getFullYear(); ;
                    trainingDateAndTime[i] = data[i].TrainingTime;
                    trainingLocation[i] = data[i].Location;
                }
                if(data.length == 0){
                    $("#selecTable").hide();
                    $("#btnSelectDate").hide();
                    $("#noAvailableDates").show();
                    
                }
                $("#calendar_Training").datepicker("setDate",new Date()); 
                
                $('#dialog_TrainingDetail').show();
                $('#dialog_TrainingDetail').dialog('open');
                $("#dialog_GroupName").html($("#groupName_"+groupID).html() +":");
                $("#dialog_TrainingName").html($("#trainingName_"+trainingID).html());
                $("#dialog_TrainingPrice").html("$"+$("#p_"+trainingID).val());    
                $("#dialog_TrainingDuration").html($("#duration_"+trainingID).val());    
            }
    });


   
   //var message = "Your purchase request was submitted. You will be notified when it has been approved";
  
   //$("#dialog_ConfirmMessage").html(message);
        
}

function selectSeat()
{
    if( $("#trainingDate").val() == ""){
        $("#selectSeat").show('normal');
        $("#selectSeatImg").show('normal');
        
    }
    else{
       $('#dialog_TrainingDetail').dialog('close');
       $(".btnRegister").click();
    }   

}
function create_Legal_Dialog()
{
   $(document).ready(function(){
        $("#dialog_Legal").load("training_legal.htm", function(){
            $("#dialog_Legal").dialog({ 
                autoOpen: false,
                buttons: { 
                    "Decline": function() { 
                            $(this).dialog("close");
                     },
                     "Accept": function() { 
                            if(IsScrollAtBottom()){
                                $(this).dialog("close");
                                registerUser();
                            }
                     }

               },
               resizable: true,
               autoResize:true,
               width: 740,
               height: 580,
               modal: true, 
               overlay: { opacity: 0.5, background: "#404040" } 
               }
             );
         });
   });
}

function create_Legal_Dialog_Info(autoShow)
{
   $(document).ready(function(){
        $("#dialog_Legal").load("training_legal.htm", function(){
            $("#dialog_Legal").dialog({ 
                autoOpen: autoShow,
                buttons: { 
                    "Close": function() { 
                            $(this).dialog("close");
                     }
               },
               resizable: true,
               autoResize:true,
               width: 740,
               height: 580,
               modal: true, 
               overlay: { opacity: 0.5, background: "#404040" } 
               }
             );
         });
   });
}

function show_Legal_Dialog()
{
 $(document).ready(function(){
    $('#dialog_Legal').show();
    $('#dialog_Legal').dialog('open');
  });
}

function showTerms(autoShow)
{
    $(document).ready(function(){
        create_Legal_Dialog_Info(autoShow);
    });
}

//http://yelotofu.com/2008/10/jquery-how-to-tell-if-youre-scroll-to-bottom/
function IsScrollAtBottom()
{
    var elem = $('#dialog_Legal');
    var inner = $('#dialog_Legal > .legalText');
    if ( Math.abs(inner.offset().top) + elem.height() + elem.offset().top >= (inner.outerHeight() - 13) ) {
      
      return true;
    }
    $('#dialog_Legal').dialog('option', 'title', 'Registration Agreement - Please read everything before accepting:');
    $(".legalText").addClass("readAll");
    return false;
}


function isScrollBottom() {
  var documentHeight = $(document).height();
  var scrollPosition = $(window).height() + $(window).scrollTop();
  return (documentHeight == scrollPosition);
} 
                
// **************************************************************************************
// Training Register Page 
// **************************************************************************************
function registerUser()
{
    var u = new Object();
    u.FirstName       =  $("#txtFirstName").val(); 
    u.LastName        =  $("#txtLastName").val(); 
    u.AddressLine1    =  $("#txtAddressLine1").val();
    u.AddressLine2    =  $("#txtAddressLine2").val();
    u.City            =  $("#txtCity").val();
    u.State           =  $("#ddState").val();
    u.ZIP             =  $("#txtZIP").val();
    u.Email           =  $("#txtEmail").val();
    u.HomePhone       =  $("#txtHomePhone").val();
    u.CellPhone       =  $("#txtCellPhone").val();
    u.TrainingID      =  $(".trainingID").val();
    u.TrainingDate    =  $(".trainingDate").val();
    u.TrainingDateID    =  $(".trainingDateID").val();
    $.ajax({
        type: "POST",
        url: servicePath + 'RegisterUserForTraining',
        data: "{'TrainingID':'"+u.TrainingID +"','TrainingDate':'"+u.TrainingDate +"','TrainingDateID':'"+ u.TrainingDateID +"','FirstName':'"+u.FirstName +"','LastName':'"+u.LastName +"','AddressLine1':'"+u.AddressLine1 +"','AddressLine2':'"+u.AddressLine2 +"','City':'"+u.City +"','State':'"+u.State +"','ZIP':'"+u.ZIP +"','Email':'"+u.Email +"','HomePhone':'"+u.HomePhone +"','CellPhone':'"+u.CellPhone +"'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        dataFilter: function (data, type) {
        return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1');
        },
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Content-type",
         "application/json; charset=utf-8");
        },
        success: function(data) {
            $("#sid").val(data);    
            $(".btnToConfirmation").click();
        }
    });
}



function validateRegisterScreen()
{
    var inputValid = true;
    //reset global attr, lets updateAmount know if we are dealing with real numbers
    $("#txtLastName").removeClass('requiredImg');
    $("#txtFirstName").removeClass('requiredImg');
    $("#txtAddressLine1").removeClass('requiredImg');
    $("#txtCity").removeClass('requiredImg');
    $("#req_State").hide();
    $("#invalidEmail").hide();
    $("#txtZIP").removeClass('requiredImg');
    $("#txtEmail").removeClass('requiredImg');
    $("#txtHomePhone").removeClass('requiredImg');
    
    if(registerClicked){
   
        if($("#txtLastName").val() == ""){
            inputValid = false;
            $("#txtLastName").addClass('requiredImg');
        }
        if($("#txtFirstName").val() == ""){
            inputValid = false;
            $("#txtFirstName").addClass('requiredImg');
        }
        if($("#txtAddressLine1").val() == ""){
            inputValid = false;
            $("#txtAddressLine1").addClass('requiredImg');
        }
        if($("#txtCity").val() == ""){
            inputValid = false;
            $("#txtCity").addClass('requiredImg');
        }
        if($("#ddState").val() == ""){
            inputValid = false;
            $("#req_State").show();
        }
        if($("#txtZIP").val() == ""){
            inputValid = false;
            $("#txtZIP").addClass('requiredImg');
        }
        if($("#txtEmail").val() == ""){
            inputValid = false;
            $("#txtEmail").addClass('requiredImg');
        }
        if(checkEmail($("#txtEmail").val()) == ""){
            inputValid = false;
            $("#txtEmail").addClass('requiredImg');
            $("#invalidEmail").show();
        }
        if($("#txtHomePhone").val() == ""){
            inputValid = false;
            $("#txtHomePhone").addClass('requiredImg');
        }        
    }
    return inputValid;
}

function setRegisterTraining_Events()
{
    $(".txtValidate").bind("change", function(e){
        validateRegisterScreen();
    });    
}

function checkEmail(emailAddr) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailAddr)){
        return (true)
    }
    return (false)
}

//Format Date
	function formatDate(d, shortDate, abbrDate) {
		var returnDate;
		if (shortDate) {
				if(abbrDate){
				    returnDate = monthNamesShort[d.getMonth()]  +' ' + d.getDate();
				}
				else{
				    returnDate = d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear();
				}
		}
		else {
			var hours = d.getHours();
			var am_pm;
			if (hours > 11) {
				am_pm = "PM";
				hours -= 12;
			} else {
				am_pm = "AM";
			}
			returnDate = d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear() + " " + hours + ":" + d.getMinutes() + " " + am_pm;
		}
		return returnDate;
	}
	
	function formatTime(t){
	    var returnDate;
	    if(t != null || t != ""){
	        var hours = t.getHours();
		    var am_pm;
		    if (hours > 11) {
			    am_pm = "PM";
			    hours -= 12;
			    if(hours == 0){
			        hours = 12;
			    }
		    } else {
			    am_pm = "AM";
		    }
		    var min = t.getMinutes();
		    if(min < 10){
		        min = "0" +min;
		    }
		    returnDate = hours + ":" + min + " " + am_pm;
		}
		return returnDate;
	}
