/*
Javascript for the application page.
3Holds all the logic for navigation, validation, and submission

*/


CLEI_Application = {

total : 0,
stop_pts: null,
app_form: null,
len: null,
curr: null,
nav_box: 'cf-sb',
req_txt: 'reqtxt',
email_txt: 'emailreqtxt',
nav_box_el: null,
sbt_btn: null,
email_index: null,
email: null,
single_mail: null,
req_list: null,
labels: [],
fields: [],
start_end: [],
lifield_bx: [],
drop_down: [],
cust_flds: [],
date_info: null,
intense_info: null,
accomm_info: null,
guide: null,
curr_hover_ref: null,
curr_hover_id: null,
startDate: null,
endDate: null,
releaseDateAlert: false,
canSubmit: false,
daysDiff: 0,

//initiate function
init: function(tot, stp_pts, eml_index, custom){
this.total = tot - 2;
this.curr = 0;
this.stop_pts = stp_pts;
this.len = stp_pts.length;
this.email_index = eml_index;
this.app_form = document.getElementById('cforms2form');
this.email = this.classElements(this.email_txt);
this.createDropDown();
this.lifield_bx = this.classElements('cf-ol');
var chNodes = this.lifield_bx[0].childNodes;
var lastEl = [];
for(a = 0, b = 0; a < chNodes.length; a++){


if(chNodes[a].nodeName == 'LI'){
lastEl[b] = chNodes[a];
b++;
}
}

this.lifield_bx[0].insertBefore(this.drop_down[0], lastEl[this.total - 2]);
this.lifield_bx[0].insertBefore(this.drop_down[1], lastEl[this.total - 2]);
this.clear_all();
this.cust_flds = custom;


for(i=1; i < this.stop_pts[1] + 1; i++){
this.labels[i - 1] = document.getElementById('li-2-'+i);
this.labels[i - 1].style.display = 'block';
this.fields[i - 1] = document.getElementById('cf2_field_'+i);
this.fields[i - 1].onblur = new Function("CLEI_Application.check_req(this)");
}


this.layout_nav();
this.setReqList();

this.date_info = "Classes at Community run in <div class=\"alertCheck\">one-week</div> increments, " +
"and they range from <div class=\"alertCheck\">one</div> to <div class=\"alertCheck\">four</div> weeks long.  " +
"We definitely accept students looking to stay for longer, " +
"but we cannot give you an exact price right now.";

this.intense_info = "Standard - Designed for people who want the best mix between learning with us," +
" and enjoying more time to delve into the city. <br/><br/> " +
"Intensive - Designed for business travelers or anyone looking to focus their time" +
" on learning Spanish. Intense courses are easier to tailor for your learning" +
"needs.";

this.accomm_info = "Homestay - Our pre-selected Dominican homes are safe and comprable with middle-class" +
" homes in North America. <br/><br/>" +
"Private - Pricing is seasonal, and it will also depend on your taste. Santiago has an " +
"array of choices from luxurious hotels to furnished apartments. ";

this.classElements('sendbutton')[0].style.height = '32px';
this.classElements('sendbutton')[0].style.paddingTop = '4px';
this.classElements('sendbutton')[0].style.position = 'relative';
this.classElements('sendbutton')[0].style.width = '77px';

this.app_form.onsubmit = function (){
return CLEI_Application.leaveStay();

}
},

leaveStay: function(){

var leave_stay = false;
var comments = '';
var stoppage;

if(this.curr == 1 || this.curr == 0){
stoppage = this.stop_pts[1];
} 
else{
stoppage = this.req_list.length;
}

for(k = 0; k < stoppage; k++){

if(this.fields[k].value == '' && k != 10){
this.fields[k].style.border = '1px solid red';
this.req_list[k].style.color = "red";
this.req_list[k].fontSize = "13px";
leave_stay = true;
}

}

if(leave_stay){

return false;
}
else{
comments = this.drop_down[0].childNodes[1].value;
comments += '  ';
comments += this.drop_down[1].childNodes[1].value;
this.fields[this.fields.length - 1].value += comments;
return true;
}

},

createDropDown: function(){

var newdiv = document.createElement('div');
var intns = "<label for=\"drop_menu\"> <span> Intensity </span></label>" +
"<select name=\"drop_menu\" id=\"drop_menu\" onclick=\" CLEI_Application.addtnInfo(2, this) \"> \n" +
"<option selected value=\"Standard\"> Standard (4 hours a day) \n" +
"<option value=\"Intensive\"> Intensive (6 hours a day) \n" +
"</select>";
newdiv.setAttribute('id', 'intensity');
newdiv.setAttribute('class', 'addtnl');
newdiv.innerHTML = intns;
newdiv.style.display = 'none';
this.drop_down[0] = newdiv;

newdiv = document.createElement('div');
var acc = "<label for=\"drop_menu\"> <span> Accommodations </span></label>" +
"<select name=\"drop_menu\" id=\"drop_menu\" onclick =\" CLEI_Application.addtnInfo(3, this) \"> \n" +
"<option selected value=\"Dominican Homestay\"> Dominican Homestay \n" +
"<option value=\"Private Apartment\"> Private Apartment \n" +
"</select>";
newdiv.setAttribute('id', 'accommdation');
newdiv.setAttribute('class', 'addtnl');
newdiv.innerHTML = acc;
newdiv.style.display = 'none';
this.drop_down[1] = newdiv;


},

//switch page function
switch_page: function(curr_page){
var old = this.curr;
this.curr = Number(curr_page.value);
this.guide = document.getElementById('guide');


var leave_stay = false;
for(k = 0; k < this.fields.length; k++){

if(this.fields[k].value == '' && k != 10){
this.fields[k].style.border = '1px solid red';
this.req_list[k].style.color = "red";
this.req_list[k].fontSize = "13px";
leave_stay = true;
}

}

if(leave_stay){
return;
}


else{
for(j = 0; j < this.fields.length; j++){

if(j == 11 || j == 12 || j == 10){
continue;
}


this.fields[j].style.border = 'none';
this.req_list[j].style.color = "#888888";
this.req_list[j].fontSize = "11px";
}
}

this.clear_all();

this.display_formel();
var submitButton = this.classElements('sendbutton')[1];;


if((old == 1 || old == 0) && this.curr == 2){

this.drop_down[0].style.display = 'block';
this.drop_down[1].style.display = 'block';

this.guide.style.display = 'block';
submitButton.style.display = 'none';
//this.changeInputType(submitButton, 'submit', 'Submit');
this.classElements('sendbutton')[0].style.display = 'inline';
this.canSubmit = true;

}

else{
this.classElements('sendbutton')[0].style.display = 'none';
submitButton.style.display = 'inline';
//this.changeInputType(submitButton, 'text', '2');
this.drop_down[0].style.display = 'none';
this.drop_down[1].style.display = 'none';
this.guide.style.display = 'none';

}

this.setReqList();

},


//display Form elements
display_formel: function(){

var one = this.curr - 1;
if(one === 0){
one = 1;
}
else{
one = this.stop_pts[this.curr - 1] + 1;
}

var two = this.curr;

if(two == this.len){
two = this.total + 1;
}
else{
two = this.stop_pts[this.curr] + 1;
}


for(i= one; i < two; i++){
this.labels[i - 1] = document.getElementById('li-2-'+i);
this.labels[i - 1].style.display = 'block';
this.fields[i - 1] = document.getElementById('cf2_field_'+i);
this.fields[i - 1].onblur = new Function("CLEI_Application.check_req(this)");

if(i == 9 || i == 10){
this.fields[i - 1].style.backgroundImage = 'url(\"/wp-content/themes/clei_home/img/calendar.png\")';
this.fields[i - 1].style.backgroundPosition = 'top right';
this.fields[i - 1].style.backgroundRepeat = 'no-repeat';
this.fields[i - 1].onfocus = new Function ("showCalendarControl(this)");
this.fields[i - 1].onclick = new Function ("CLEI_Application.addtnInfo(1, this)");
this.fields[i - 1].onblur = function(){};
}

if(i == 12){

this.labels[i -1].style.display = 'none';

}


}
},

//clear all
clear_all: function(){

for(i=1; i < this.total + 1; i++){
document.getElementById('li-2-'+i).style.display = 'none';
}

},

addtnInfo: function(val, ref){
this.curr_hover_ref = ref;
this.curr_hover_id = ref.id;
this.curr_hover_ref.value = '';

switch(val){

case 1: 

document.getElementById('dyn_guide').innerHTML = this.date_info;

break;

case 2: document.getElementById('dyn_guide').innerHTML = this.intense_info;

break;

case 3: document.getElementById('dyn_guide').innerHTML = this.accomm_info;

break;

}

this.packagePrice();
},

changeInputType: function(oldObject, oType, oValue) {
var newObject = document.createElement('input');
newObject.type = oType;
newObject.value = oValue;
if(oldObject.size) newObject.size = oldObject.size;
if(oldObject.name) newObject.name = oldObject.name;
if(oldObject.id) newObject.id = oldObject.id;
if(oldObject.className) newObject.className = oldObject.className;
oldObject.parentNode.replaceChild(newObject,oldObject);
return newObject;
},


//layout nav
layout_nav: function(){
this.setNavBoxEl(this.nav_box);

for(i=this.len; i > 0; i--){
this.addMenuItem(i);

}
},


//addMenuItem
addMenuItem: function(val) {

var numi = this.nav_box_el[0];
var newdiv = document.createElement('div');
var divIdName = 'layout_nav';
var innerHTML = '<input type="buttom" value="'+ val +'" class="sendbutton" id="sendbutton3" name="sendbutton2" onClick="CLEI_Application.switch_page(this);"/>';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = innerHTML;
this.sbt_btn = numi.childNodes[0];
this.sbt_btn.style.display = 'none';
numi.appendChild(newdiv);
},

//SetNavBoxEl
setNavBoxEl: function(classSearch) {
var classElements = [];

var els = this.app_form.getElementsByTagName('*');
var elsLen = els.length;
var pattern = new RegExp('(^|\\\\s)'+classSearch+'(\\\\s|$)');
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
this.nav_box_el = classElements;
},

//ReqElements
reqElements: function(classSearch){
var classElements = [];
var els = this.app_form.getElementsByTagName('*');
var elsLen = els.length;
var pattern = new RegExp('(^|\\\\s)'+classSearch+'(\\\\s|$)');
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {

classElements[j] = els[i];
j++;
}
}
return classElements;
},

//Class elements
classElements: function(classSearch){
var classElements = [];
var els = this.app_form.getElementsByTagName('*');
var elsLen = els.length;
var pattern = new RegExp('(^|\\\\s)'+classSearch+'(\\\\s|$)');
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
},

//Email Span
emailSpan: function(){

var newSpan = document.createElement('span');
var innerHTML = '(required)';
newSpan.setAttribute('id', '');
newSpan.setAttribute('class', 'reqtxt');
newSpan.innerHTML = innerHTML;
return newSpan;
},

//Check Reqs
check_req: function(req_box){

var boxLen = req_box.id.length;
var index = null;

if(boxLen < 12){
index = req_box.id.charAt(req_box.id.length - 1);
}
else{
index = req_box.id.charAt(req_box.id.length - 2) + req_box.id.charAt(req_box.id.length - 1);
}

if(req_box.value === null || req_box.value == ''){

this.req_list[index - 1].style.color = "red";
this.req_list[index - 1].style.fontSize = "13px";

}else{
this.fields[index - 1].style.border = 'none';
this.req_list[index - 1].style.color = "#888888";
this.req_list[index - 1].style.fontSize = "11px";

}


},

//Set Req List
setReqList: function(){
this.req_list = this.classElements(this.req_txt);
for(i = 0; i < this.req_list.length; i++){
for(j = 0; j < this.email_index.length; j++){


if(i == this.email_index[j]){
this.req_list.splice(i - 1, 0, this.email[j]);
}
}
for(k = 0; k < this.cust_flds.length; k++){

if(i == this.cust_flds[k]){
this.req_list.splice(i - 1, 0, this.drop_down[k]);
}

}

}
},

setStart: function(yr, mon, day){
this.startDate = new Date(yr, mon, day);
this.startDate.setHours(0,0,0,0);
this.startDateFlag = true;
if(this.endDateFlag == true && this.startDateFlag == true){
this.checkDate();
}

},

setEnd: function(yr, mon, day){
this.endDate = new Date(yr, mon, day);
this.endDate.setHours(0,0,0,0);
this.endDateFlag = true;

if(this.endDateFlag == true && this.startDateFlag == true){
this.checkDate();
}

},

checkDate: function(){

var one_day=1000*60*60*24;

if(this.startDate < this.endDate){
this.releaseDateAlert = true;
this.daysDiff = Math.ceil((this.endDate.getTime() - this.startDate.getTime())/(one_day));
if((this.daysDiff%7) == 0 && this.daysDiff < 29 && this.daysDiff > 0){
this.alertDateCheck('alertCheck');
this.packagePrice();
return;
}
else{
this.alertDateCheck('alertCheckRed');
}
}

},

alertDateCheck: function(color){

switch(color){

case 'alertCheck': this.date_info = "Classes at Community run in <div class=\"alertCheck\">one-week</div> increments, " +
"and they range from <div class=\"alertCheck\">one</div> to <div class=\"alertCheck\">four</div> weeks long.  " +
"We definitely accept students looking to stay for longer, " +
"but we cannot give you an exact price right now.";
break;

case 'alertCheckRed': this.date_info = "Classes at Community run in <div class=\"alertCheckRed\">one-week</div> increments, " +
"and they range from <div class=\"alertCheckRed\">one</div> to <div class=\"alertCheckRed\">four</div> weeks long.  " +
"We definitely accept students looking to stay for longer, " +
"but we cannot give you an exact price right now.";
break;
}

document.getElementById('dyn_guide').innerHTML = this.date_info;

},

packagePrice: function(){

var wks = this.daysDiff/7;
var i = this.drop_down[0].childNodes[1].value;
var a = this.drop_down[1].childNodes[1].value;
var price;

if(a == 'Private Apartment'){

document.getElementById('curr_price').innerHTML =  "<span style=\"color: red;\">  We will contact you very soon about pricing.</span>";
return;
}

else{
document.getElementById('curr_price').innerHTML =  " Your current price is $ <span id=\"class_price\"></span>.";
}
switch(wks){

case 1: 

if(i == 'Intensive'){
price = "475";
}
else{
price = "375";
}

break;
case 2:
if(i == 'Intensive'){
price = "775";
}
else{
price = "700";
}

break;
case 3:
if(i == 'Intensive'){
price = "1100";
}
else{
price = "925";
}

break;
case 4:
if(i == 'Intensive'){
price = "1425";
}
else{
price = "1125";
}
break;

default:
price = '0';
}

document.getElementById('class_price').innerHTML = price;


}

};

function positionInfo(object) {

var p_elm = object;
this.getElementLeft = getElementLeft;
function getElementLeft() {
var x = 0;
var elm;
if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
while (elm != null) {
x+= elm.offsetLeft;
elm = elm.offsetParent;
}
return parseInt(x);
}

this.getElementWidth = getElementWidth;
function getElementWidth(){
var elm;
if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
return parseInt(elm.offsetWidth);
}

this.getElementRight = getElementRight;
function getElementRight(){
return getElementLeft(p_elm) + getElementWidth(p_elm);
}

this.getElementTop = getElementTop;
function getElementTop() {
var y = 0;
var elm;
if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
while (elm != null) {
y+= elm.offsetTop;
elm = elm.offsetParent;
}
return parseInt(y);
}

this.getElementHeight = getElementHeight;
function getElementHeight(){
var elm;
if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
return parseInt(elm.offsetHeight);
}

this.getElementBottom = getElementBottom;
function getElementBottom(){
return getElementTop(p_elm) + getElementHeight(p_elm);
}
}

function CalendarControl() {

var calendarId = 'CalendarControl';
var currentYear = 0;
var currentMonth = 0;
var currentDay = 0;

var selectedYear = 0;
var selectedMonth = 0;
var selectedDay = 0;

var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var dateField = null;

function getProperty(p_property){
var p_elm = calendarId;
var elm = null;

if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
if (elm != null){
if(elm.style){
elm = elm.style;
if(elm[p_property]){
return elm[p_property];
} else {
return null;
}
} else {
return null;
}
}
}

function setElementProperty(p_property, p_value, p_elmId){
var p_elm = p_elmId;
var elm = null;

if(typeof(p_elm) == "object"){
elm = p_elm;
} else {
elm = document.getElementById(p_elm);
}
if((elm != null) && (elm.style != null)){
elm = elm.style;
elm[ p_property ] = p_value;
}
}

function setProperty(p_property, p_value) {
setElementProperty(p_property, p_value, calendarId);
}

function getDaysInMonth(year, month) {
return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
}

function getDayOfWeek(year, month, day) {
var date = new Date(year,month-1,day)
return date.getDay();
}

this.clearDate = clearDate;
function clearDate() {
dateField.value = '';
hide();
}

this.setDate = setDate;
function setDate(year, month, day) {
if (dateField) {
if (month < 10) {month = "0" + month;}
if (day < 10) {day = "0" + day;}

var dateString = month+"/"+day+"/"+year;
dateField.value = dateString;
if(CLEI_Application.curr_hover_id == 'cf2_field_9'){
CLEI_Application.setStart(year, month - 1, day);

}

if(CLEI_Application.curr_hover_id == 'cf2_field_10'){
CLEI_Application.setEnd(year, month - 1, day);

}

hide();
}
return;
}

this.changeMonth = changeMonth;
function changeMonth(change) {
currentMonth += change;
currentDay = 0;
if(currentMonth > 12) {
currentMonth = 1;
currentYear++;
} else if(currentMonth < 1) {
currentMonth = 12;
currentYear--;
}

calendar = document.getElementById(calendarId);
calendar.innerHTML = calendarDrawTable();
}

this.changeYear = changeYear;
function changeYear(change) {
currentYear += change;
currentDay = 0;
calendar = document.getElementById(calendarId);
calendar.innerHTML = calendarDrawTable();
}

function getCurrentYear() {
var year = new Date().getYear();
if(year < 1900) year += 1900;
return year;
}

function getCurrentMonth() {
return new Date().getMonth() + 1;
}

function getCurrentDay() {
return new Date().getDate();
}

function calendarDrawTable() {

var dayOfMonth = 1;
var validDay = 0;
var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
var daysInMonth = getDaysInMonth(currentYear, currentMonth);
var css_class = null; //CSS class for each day

var table = "<table cellspacing='0' cellpadding='0' border='0'>";
table = table + "<tr class='header'>";
table = table + " <td colspan='2' class='previous'><a href='javascript:changeCalendarControlMonth(-1);'>&lt;</a> <a href='javascript:changeCalendarControlYear(-1);'>&laquo;</a></td>";
table = table + " <td colspan='3' class='title'>" + months[currentMonth-1] + "<br>" + currentYear + "</td>";
table = table + " <td colspan='2' class='next'><a href='javascript:changeCalendarControlYear(1);'>&raquo;</a> <a href='javascript:changeCalendarControlMonth(1);'>&gt;</a></td>";
table = table + "</tr>";
table = table + "<tr><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>";

for(var week=0; week < 6; week++) {
table = table + "<tr>";
for(var dayOfWeek=0; dayOfWeek < 7; dayOfWeek++) {
if(week == 0 && startDayOfWeek == dayOfWeek) {
validDay = 1;
} else if (validDay == 1 && dayOfMonth > daysInMonth) {
validDay = 0;
}

if(validDay) {
if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
css_class = 'current';
} else if (dayOfWeek == 0 || dayOfWeek == 6) {
css_class = 'weekend';
} else {
css_class = 'weekday';
}

table = table + "<td><a class='"+css_class+"' href=\"javascript:setCalendarControlDate("+currentYear+","+currentMonth+","+dayOfMonth+")\">"+dayOfMonth+"</a></td>";
dayOfMonth++;
} else {
table = table + "<td class='empty'>&nbsp;</td>";
}
}
table = table + "</tr>";
}

table = table + "<tr class='header'><th colspan='7' style='padding: 3px;'><a href='javascript:clearCalendarControl();'>Clear</a> | <a href='javascript:hideCalendarControl();'>Close</a></td></tr>";
table = table + "</table>";

return table;
}

this.show = show;
function show(field) {
can_hide = 0;

// If the calendar is visible and associated with
// this field do not do anything.
if (dateField == field) {
return;
} else {
dateField = field;
}

if(dateField) {
try {
var dateString = new String(dateField.value);
var dateParts = dateString.split("-");

selectedMonth = parseInt(dateParts[0],10);
selectedDay = parseInt(dateParts[1],10);
selectedYear = parseInt(dateParts[2],10);
} catch(e) {}
}

if (!(selectedYear && selectedMonth && selectedDay)) {
selectedMonth = getCurrentMonth();
selectedDay = getCurrentDay();
selectedYear = getCurrentYear();
}

currentMonth = selectedMonth;
currentDay = selectedDay;
currentYear = selectedYear;

if(document.getElementById){

calendar = document.getElementById(calendarId);
calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);

setProperty('display', 'block');

var fieldPos = new positionInfo(dateField);
var calendarPos = new positionInfo(calendarId);

var x = fieldPos.getElementLeft();
var y = fieldPos.getElementBottom();

setProperty('left', x + "px");
setProperty('top', y + "px");

if (document.all) {
setElementProperty('display', 'block', 'CalendarControlIFrame');
setElementProperty('left', x + "px", 'CalendarControlIFrame');
setElementProperty('top', y + "px", 'CalendarControlIFrame');
setElementProperty('width', calendarPos.getElementWidth() + "px", 'CalendarControlIFrame');
setElementProperty('height', calendarPos.getElementHeight() + "px", 'CalendarControlIFrame');
}
}
}

this.hide = hide;
function hide() {
if(dateField) {
setProperty('display', 'none');
setElementProperty('display', 'none', 'CalendarControlIFrame');
dateField = null;
}


CLEI_Application.check_req(document.getElementById(CLEI_Application.curr_hover_id));
}

this.visible = visible;
function visible() {
return dateField
}

this.can_hide = can_hide;
var can_hide = 0;
}

var calendarControl = new CalendarControl();

function showCalendarControl(textField) {
// textField.onblur = hideCalendarControl;
calendarControl.show(textField);
}

function clearCalendarControl() {
calendarControl.clearDate();
}

function hideCalendarControl() {
if (calendarControl.visible()) {
calendarControl.hide();
}
}

function setCalendarControlDate(year, month, day) {
calendarControl.setDate(year, month, day);
}

function changeCalendarControlYear(change) {
calendarControl.changeYear(change);
}

function changeCalendarControlMonth(change) {
calendarControl.changeMonth(change);
}

document.write("<iframe id='CalendarControlIFrame' src='javascript:false;' frameBorder='0' scrolling='no'></iframe>");
document.write("<div id='CalendarControl'></div>");