// JavaScript Document
irise.namespace("irise"); // sets the namespace

var jsiPhoneDTPVObjArr = new Array(); // data for all instances of the Flex component
var jsiPhoneDTPVInstanceArr = new Array(); // reference to all instances of the Flex component
var jsiPhoneDTPVKey = 0; // holds the id of the instance being loaded
var inFocusWidgetDTPVJS; // in place for the blur event
var gmgWrkArndFrScrlStop;
var mouseDownGMGDTPV;
irise.iPhoneDateTimePickerVertical = function(){
}

irise.iPhoneDateTimePickerVertical.prototype.onload = function(){

try{
        this.getWidgetDiv().width(320);
        this.getWidgetDiv().height(214);
        var i;
		var me = this;
		// shortening large identifiers
        var fullId = this.getId();
        var id = fullId.substring(fullId.length-4);
        jsiPhoneDTPVKey = id; // store the shortened instance id to be used as array element key
        // if(!flexiPhoneDPPInstanceArr[flexiPhoneDPPKey]){     // execute rest of the code only if the onload function was not called before 
		jsiPhoneDTPVInstanceArr[jsiPhoneDTPVKey] = this;   // store the current instance of the widget
		var DTPVObject = {};
		// look-up table for months
		var monthsArray = new Array(12);
			monthsArray[0] = "January";
			monthsArray[1] = "February";
			monthsArray[2] = "March";
			monthsArray[3] = "April";
			monthsArray[4] = "May";
			monthsArray[5] = "June";
			monthsArray[6] = "July";
			monthsArray[7] = "August";
			monthsArray[8] = "September";
			monthsArray[9] = "October";
			monthsArray[10] = "November";
			monthsArray[11] = "December";
		// look-up table for months
		var monthsShortArray = new Array(12);
			monthsShortArray[0] = "Jan";
			monthsShortArray[1] = "Feb";
			monthsShortArray[2] = "Mar";
			monthsShortArray[3] = "Apr";
			monthsShortArray[4] = "May";
			monthsShortArray[5] = "Jun";
			monthsShortArray[6] = "Jul";
			monthsShortArray[7] = "Aug";
			monthsShortArray[8] = "Sep";
			monthsShortArray[9] = "Oct";
			monthsShortArray[10] = "Nov";
			monthsShortArray[11] = "Dec";
		// look-up table for days
		var weekdaysArray=new Array(7);
			weekdaysArray[0]="Sun";
			weekdaysArray[1]="Mon";
			weekdaysArray[2]="Tue";
			weekdaysArray[3]="Wed";
			weekdaysArray[4]="Thu";
			weekdaysArray[5]="Fri";
			weekdaysArray[6]="Sat";
		// look-up table for minutes
		var minutesArray=new Array(12);
			minutesArray[0]="00";
			minutesArray[1]="05";
			minutesArray[2]="10";
			minutesArray[3]="15";
			minutesArray[4]="20";
			minutesArray[5]="25";
			minutesArray[6]="30";
			minutesArray[7]="35";
			minutesArray[8]="40";
			minutesArray[9]="45";
			minutesArray[10]="50";
			minutesArray[11]="55";
		// get current date
		var currentDate = new Date();
		// get the total days in the current month
		var tempDate = new Date(currentDate.getFullYear(), currentDate.getMonth()+1, 0);
		var totalDays = tempDate.getDate();
		// get in-focus values
		var inFocusYear = currentDate.getFullYear();
		var inFocusMonth = currentDate.getMonth();
		var inFocusDate = currentDate.getDate();
		var inFocusDay = currentDate.getDay();
		var inFocus24Hour = currentDate.getHours();
		var inFocusAMPM = (inFocus24Hour > 11)? "PM":"AM";
		var inFocusHour = ((inFocus24Hour > 12) && (inFocus24Hour < 24))? (inFocus24Hour - 12):inFocus24Hour;
		var inFocusMinute = currentDate.getMinutes() - (currentDate.getMinutes()%5);
		var inFocusMinuteIndex = inFocusMinute/5;
		var millisecondsPerDay = 1000 * 60 * 60 * 24;
}
catch(e){
	alert("Error in first part(initializations): "+e.description);
}		
		
		var customizeForDevice = function(){
			var ua = navigator.userAgent;
			var checker = {
				iphone: ua.match(/(iPhone|iPod|iPad)/),
				blackberry: ua.match(/BlackBerry/),
				android: ua.match(/Android/)
			};
			if (checker.android || checker.iphone || checker.blackberry)
				return true;
			else
				return false;
		}
		
		if(customizeForDevice()){
			document.addEventListener("touchstart", me.touchHandler, true);
			document.addEventListener("touchmove", me.touchHandler, true);
			document.addEventListener("touchend", me.touchHandler, true);
		}
try{
		// retrieve the widget properties
		var dPickerDataFormat = this.getProperty('dpDataFormat');
		var dPickerSelDate = this.getProperty('dpSelectedDate');
		if(dPickerSelDate == "" || dPickerSelDate == null || dPickerSelDate == "undefined"){
			dPickerSelDate = "";
		}
		else{
			var validDate = validateDateDTPVJS(dPickerSelDate, dPickerDataFormat);
			if(validDate.isCorrect){
				if(validDate.year)
					inFocusYear = parseInt(validDate.year, 10);
				inFocusMonth = parseInt(validDate.month, 10);
				inFocusDate = parseInt(validDate.date, 10);
				inFocusHour = parseInt(validDate.hour, 10);
				if(inFocusHour != 12)
					inFocus24Hour = (inFocusAMPM == "AM")? inFocusHour : inFocusHour + 12;
				else
					inFocus24Hour = (inFocusAMPM == "AM")? 0 : inFocusHour;
				inFocusAMPM = validDate.ampm;
				inFocusMinute = parseInt(validDate.minute, 10);
				inFocusMinuteIndex = inFocusMinute/5;
				var tempDateForDay = new Date(inFocusYear, inFocusMonth, inFocusDate, inFocus24Hour, inFocusMinute, 0);
				inFocusDay = tempDateForDay.getDay();
			}
		}
		var dPickerTagertWidget = this.getProperty('dpTargtWidget');
		if(dPickerTagertWidget == "" || dPickerTagertWidget == null || dPickerTagertWidget == "undefined"){
				dPickerTagertWidget = "";	// no need to check the autoshow field
		}
		var dPickerFontFamily = this.getProperty('dpFontFamily');
		var dPickerFontSize = this.getProperty('dpFontSize');
		if(dPickerFontSize == "" || dPickerFontSize == null || dPickerFontSize == "undefined" || dPickerFontSize > 25 || dPickerFontSize < 18)
			dPickerFontSize = "24";
		var dPickerFontColor = this.getProperty('dpFontColor');
		if(dPickerFontColor == "" || dPickerFontColor == null || dPickerFontColor == "undefined")
			dPickerFontColor = "#000000";
		var dPickerFontWeight = this.getProperty('dpFontWeight');
		if(dPickerFontWeight === null || dPickerFontWeight === 'undefined' || dPickerFontWeight === false)
			dPickerFontWeight = 'normal';
		else
			dPickerFontWeight = 'bold';
		// font size corrections for proper rendering of the widget
		if (dPickerFontFamily == "Arial Black" || dPickerFontFamily == "Verdana"){
			if (dPickerFontSize > 20)
				dPickerFontSize = 20;
		}
		else if (dPickerFontFamily == "Bookman Old Style" || dPickerFontFamily == "Georgia" || dPickerFontFamily == "Lucida Sans Unicode" || dPickerFontFamily == "Tahoma"){
			if (dPickerFontSize > 21)
				dPickerFontSize = 21;
		}
		else if (dPickerFontFamily == "Microsoft Sans Serif" || dPickerFontFamily == "Century"){
			if (dPickerFontSize > 22)
				dPickerFontSize = 22;
		}
		else if (dPickerFontFamily == "Franklin Gothic Medium"){
			if (dPickerFontSize > 23)
				dPickerFontSize = 23;
		}
		
		// populate the object with data
		DTPVObject = {
			'dateTimePickerSelectedDate' : dPickerSelDate,
			'dateTimePickerDateFormat' : dPickerDataFormat,
			'dateTimePickerFontFamily' : dPickerFontFamily,
			'dateTimePickerFontSize' : dPickerFontSize,
			'dateTimePickerFontColor' : dPickerFontColor,
			'dateTimePickerFontWeight' : dPickerFontWeight
		};
		// individualize the data for each instance of the flex component on the page
		jsiPhoneDTPVObjArr[jsiPhoneDTPVKey] = DTPVObject;
}
catch(e){
	alert("Error retrieving widget properties: "+e.description);
}


try{
		// 
		function setiPhoneDTPVJSProperties(vlue, fireEvent){
			me.setProperty('dpSelectedDate',vlue);  // sets the widget property
			DTPVObject.dateTimePickerSelectedDate = vlue; 
			if(dPickerTagertWidget){
					if (dPickerTagertWidget.getType() === 'widget') // if an ibloc, then use the setValue action
							dPickerTagertWidget.setValue(vlue);
					else{ 
							if(dPickerTagertWidget.getWidgetDiv().text()) // if label widget, then use html() method
									dPickerTagertWidget.getWidgetDiv().html(vlue);
							else
									dPickerTagertWidget.getWidgetDiv().val(vlue); // for all others, use the val() method
					}
			}
			if(fireEvent)
					me.sendEvent('onSelectionChange');
		}
		//
        function setIblocProperty(fireEvent){
					var tempDateStr;
					var tempMonth;
					if((inFocusMonth + 1) < 10)
						tempMonth = "0"+ (inFocusMonth + 1).toString();
					else
						tempMonth = (inFocusMonth + 1).toString();
					var halfYear = inFocusYear.toString().substr(2,2);
					var halfMonth = monthsShortArray[inFocusMonth];
					switch(dPickerDataFormat){
						case "DD/MM/YY HH:MM PM":
							tempDateStr = inFocusDate+"/"+tempMonth+"/"+halfYear+" "+inFocusHour+":"+minutesArray[inFocusMinuteIndex]+" "+inFocusAMPM;
							break;
						case "Year Month Date HH:MM PM":
							tempDateStr = inFocusYear+" "+monthsArray[inFocusMonth]+" "+inFocusDate+" "+inFocusHour+":"+minutesArray[inFocusMinuteIndex]+" "+inFocusAMPM;
							break;
						case "MM/DD/YYYY HH:MM PM":
							tempDateStr = tempMonth+"/"+inFocusDate+"/"+inFocusYear+" "+inFocusHour+":"+minutesArray[inFocusMinuteIndex]+" "+inFocusAMPM;
							break;
						case "MM/DD/YY HH:MM PM":
							tempDateStr = tempMonth+"/"+inFocusDate+"/"+halfYear+" "+inFocusHour+":"+minutesArray[inFocusMinuteIndex]+" "+inFocusAMPM;
							break;
						case "Mon Date Year HH:MM PM":
							tempDateStr = monthsShortArray[inFocusMonth]+" "+inFocusDate+" "+inFocusYear+" "+inFocusHour+":"+minutesArray[inFocusMinuteIndex]+" "+inFocusAMPM;
							break;
						case "DD/MM/YYYY HH:MM PM":
							tempDateStr = inFocusDate+"/"+tempMonth+"/"+inFocusYear+" "+inFocusHour+":"+minutesArray[inFocusMinuteIndex]+" "+inFocusAMPM;
							break;
						default:
							tempDateStr = weekdaysArray[inFocusDay]+" "+monthsShortArray[inFocusMonth]+" "+inFocusDate+" "+inFocusHour+":"+minutesArray[inFocusMinuteIndex]+" "+inFocusAMPM;
							break;
					}
					setiPhoneDTPVJSProperties(tempDateStr, fireEvent);
		}

}
catch(e){
	alert("Error in Setting widget properties: "+e.description);
}
		//------------------------------------------- begin widget code -----------------------------------

try{
		// utility function to populate the look-up arrays for the current state of the widget
		function populateStateLookupArrays(str){
			var tempArray;
			var inFocusElement;
			var startingElement;
			var finalArray = new Array();
			switch(str){
				case "dmd": // day month date 
						var tempDate = new Date(inFocusYear, inFocusMonth, inFocusDate, inFocus24Hour, inFocusMinute, 0);
						for(i = 0; i < 15; i++){
							startingElement = new Date(tempDate.getTime() - ((7-i)*millisecondsPerDay));
							finalArray[i] = new Object();
							finalArray[i].day = weekdaysArray[startingElement.getDay()];
							finalArray[i].month = monthsShortArray[startingElement.getMonth()];
							finalArray[i].date = startingElement.getDate();
						}
					break;
				case "hrs": // hours
						inFocusElement = inFocusHour;
						startingElement = inFocusElement - 7;
						if(startingElement < 0){
							startingElement = 13 + startingElement;
						}
						for(i = 0; i < 15; i++){
							if(startingElement > 12)
								startingElement = 0;
							finalArray[i] = (startingElement > 9)? startingElement:"0"+startingElement;
							startingElement++;
						}
					break;
				case "mts": // minutes
						inFocusElement = inFocusMinuteIndex;
						startingElement = inFocusElement - 7;
						if(startingElement < 0){
							startingElement = 12 + startingElement;
						}
						for(i = 0; i < 15; i++){
							if(startingElement > 11)
								startingElement = 0;
							finalArray[i] = minutesArray[startingElement];
							startingElement++;
						}
					break;
				case "amp": // minutes
						switch(inFocusAMPM){
							case "AM":
								for(i = 0; i < 15; i++){
									if(i == 7)
										finalArray[i] = "AM";
									else if(i == 8)
										finalArray[i] = "PM";
									else
										finalArray[i] = " ";
								}
								break;
							case "PM":
								for(i = 0; i < 15; i++){
									if(i == 6)
										finalArray[i] = "AM";
									else if(i == 7)
										finalArray[i] = "PM";
									else
										finalArray[i] = " ";
								}
								break;
						}
					break;
			}
			return finalArray;
		};
		//the current state look-up arrays
		var currentDmdArray = populateStateLookupArrays("dmd");
		var currentHourArray = populateStateLookupArrays("hrs");
		var currentMinuteArray = populateStateLookupArrays("mts");
		var currentAMPMArray = populateStateLookupArrays("amp");
}
catch(e){
	alert("Error populating state lookup arrays: "+e.description);
}

try{
		$('<div class="containerDivJSDTPV"><div class="innerDivJSDTPV"></div></div>').appendTo('#'+fullId);
		// utility function to populate the inner div with columns and rows within
		function populateColumns(divClass){
			var toAddDiv;
			var rowDivs = "";
			switch(divClass){
				case "firstColumn": // the day month date column
					for(i = 0; i < 15; i++){
						rowDivs = rowDivs + '<div class = "rowDmdJSDTPV"><span class = "daySpan"></span>&nbsp;<span class = "monthSpan"></span>&nbsp;<span class = "dateSpan"></span></div>';
					} 
					toAddDiv = '<div class="ui-widget-content-JSDTPV firstColumnJSDTPV">'+rowDivs+'</div>';
					break;
				case "secondColumn": // the hours column
					for(i = 0; i < 15; i++){
						rowDivs = rowDivs + '<div class = "rowDivJSDTPV"></div>';
					}
					toAddDiv = '<div class="ui-widget-content-JSDTPV secondColumnJSDTPV">'+rowDivs+'</div>';
					break;
				case "thirdColumn": // the minutes column
					for(i = 0; i < 15; i++){
						rowDivs = rowDivs + '<div class = "rowDivJSDTPV"></div>';
					}
					toAddDiv = '<div class="ui-widget-content-JSDTPV thirdColumnJSDTPV">'+rowDivs+'</div>';
					break;
				case "fourthColumn":
					for(i = 0; i < 15; i++){
						rowDivs = rowDivs + '<div class = "rowDivJSDTPV"></div>';
					}
					toAddDiv = '<div class="ui-widget-content-JSDTPV fourthColumnJSDTPV">'+rowDivs+'</div>';
					break;
			}
			var divObj = { 'theDiv' : toAddDiv, 'theColumn' : divClass};
			return divObj;
		}
		// append the populated divs to the page
		$('#'+fullId+' .innerDivJSDTPV').append(populateColumns("firstColumn").theDiv);
		$('#'+fullId+' .innerDivJSDTPV').append('<div class="spacerDivJSDTPV"></div>');
		$('#'+fullId+' .innerDivJSDTPV').append(populateColumns("secondColumn").theDiv);
		$('#'+fullId+' .innerDivJSDTPV').append('<div class="spacerDivJSDTPV"></div>');
		$('#'+fullId+' .innerDivJSDTPV').append(populateColumns("thirdColumn").theDiv);
		$('#'+fullId+' .innerDivJSDTPV').append('<div class="spacerDivJSDTPV"></div>');
		$('#'+fullId+' .innerDivJSDTPV').append(populateColumns("fourthColumn").theDiv);
		
		// utility function to populate the data for each row
		function populateRowData(str){
			var childrenArray = $('#'+fullId+' .innerDivJSDTPV .'+str+'JSDTPV').children();
			var tempCurrentArray;
			switch(str){
				case "firstColumn":
					tempCurrentArray = currentDmdArray;
					for(i = 0; i < 15; i++){
						var spanChildren = $(childrenArray[i]).children();
						$(spanChildren[0]).text(tempCurrentArray[i].day);
						$(spanChildren[0]).css({'color': dPickerFontColor, 'fontFamily': dPickerFontFamily, 'fontWeight': dPickerFontWeight, 'fontSize': dPickerFontSize-2});
						$(spanChildren[1]).text(tempCurrentArray[i].month);
						$(spanChildren[1]).css({'color': dPickerFontColor, 'fontFamily': dPickerFontFamily, 'fontWeight': dPickerFontWeight, 'fontSize': dPickerFontSize});
						$(spanChildren[2]).text(tempCurrentArray[i].date);
						$(spanChildren[2]).css({'color': dPickerFontColor, 'fontFamily': dPickerFontFamily, 'fontWeight': dPickerFontWeight, 'fontSize': dPickerFontSize});
					}
					return;
				case "secondColumn":
					tempCurrentArray = currentHourArray;
					break;
				case "thirdColumn":
					tempCurrentArray = currentMinuteArray;
					break;
				case "fourthColumn":
					tempCurrentArray = currentAMPMArray;
					break;
			}
			for(i = 0; i < 15; i++){
				$(childrenArray[i]).css({'color': dPickerFontColor, 'fontFamily': dPickerFontFamily, 'fontWeight': dPickerFontWeight, 'fontSize': dPickerFontSize});
				$(childrenArray[i]).text(tempCurrentArray[i]);
			}
		}
		// populate the rows with data
		populateRowData("firstColumn");
		populateRowData("secondColumn");
		populateRowData("thirdColumn");
		populateRowData("fourthColumn");
		
		setIblocProperty(false);
}
catch(e){
	alert("Error appending widget and populating row data: "+e.description);
}

		// ----------------------------------------------- actions -------------------------------------------------- //
try{
		// make contents draggable
		$(function() {
				$( ".ui-widget-content-JSDTPV" ).draggable({ axis: "y" });
		});
		
		var rowHeight = 39; // the default row height for each row
		var mouseDownFlag = false; // flag to distinguish move and drag
		var mouseMoveFlag = false; // flag to distinguish click and drag
		var activeColumn = null; // current column being dragged
		var notAlreadyRun = false; // stop double-execution-bug during mouse leave
		var currentActiveData = {}; // info about current active element
		// callback function for mouse down
		var mouseDownFn = function(e){
			if(customizeForDevice()){
				gmgWrkArndFrScrlStop.preventDefault();
			}
			notAlreadyRun = true;
			activeColumn = this;
			if($(activeColumn).is('.firstColumnJSDTPV'))
				currentActiveData = {'activeArray': currentDmdArray, 'column': "firstColumn"};
			else if($(activeColumn).is('.secondColumnJSDTPV'))
				currentActiveData = {'activeArray': currentHourArray, 'column': "secondColumn"};
			else if($(activeColumn).is('.thirdColumnJSDTPV'))
				currentActiveData = {'activeArray': currentMinuteArray, 'column': "thirdColumn"};
			else{
				currentActiveData = {'activeArray': currentAMPMArray, 'column': "fourthColumn"};
			}
			mouseDownFlag = true;
			if(customizeForDevice()){
				gmgWrkArndFrScrlStop = null;
			}
				// for the onBlur issue in IE when the widget is placed within a view
			if($.browser.msie){// for IE
			if(!mouseDownGMGDTPV){
				e.stopPropagation();
				$('#'+fullId+' .containerDivJSDTPV').mousedown();
				}
			}
		};
		// call back function for mouse move
		var mouseMoveFn = function(){
			if(mouseDownFlag){
				if(customizeForDevice()){
					gmgWrkArndFrScrlStop.preventDefault();
				}
				mouseMoveFlag = true;
				if(customizeForDevice()){
					gmgWrkArndFrScrlStop = null;
				}
			}
		};
		// call back function for mouse up
		var mouseUpFn = function(e){
			if(customizeForDevice()){
				gmgWrkArndFrScrlStop.preventDefault();
			}
			if(notAlreadyRun){
				notAlreadyRun = false;
				if(mouseDownFlag){
					if(mouseMoveFlag){ // ---------------------------------------------- this section handles the drag
							// determine the new inFocus value
							var tempColDivY = ($(activeColumn).offset().top - $('#'+fullId+' .innerDivJSDTPV').offset().top) - (($(activeColumn).offset().top - $('#'+fullId+' .innerDivJSDTPV').offset().top) % rowHeight);
							var tempDispY = ((Math.abs(tempColDivY) - 195)/rowHeight) - 1;
							// generate the new column
							var toAddDiv = populateColumns(currentActiveData.column).theDiv;
							// set the inFocus values to new values and re-populate the current active arrays
							switch(currentActiveData.column){
								case "firstColumn":
										var tempDate = new Date(inFocusYear, inFocusMonth, inFocusDate, inFocus24Hour, inFocusMinute, 0);
										tempDate = new Date(tempDate.getTime() +  (tempDispY+1)*millisecondsPerDay);
										inFocusYear = tempDate.getFullYear();
										inFocusMonth = tempDate.getMonth();
										inFocusDate = tempDate.getDate();
										inFocusDay = tempDate.getDay();
										currentDmdArray = populateStateLookupArrays("dmd");
									break;
								case "secondColumn":
										inFocusHour = parseInt(currentActiveData.activeArray[8 + tempDispY], 10);
										if(inFocusHour != 12)
											inFocus24Hour = (inFocusAMPM == "AM")? inFocusHour : inFocusHour + 12;
										else
											inFocus24Hour = (inFocusAMPM == "AM")? 0 : inFocusHour;
										currentHourArray = populateStateLookupArrays("hrs");
									break;
								case "thirdColumn":
										inFocusMinute = parseInt(currentActiveData.activeArray[8 + tempDispY], 10);
										inFocusMinuteIndex = inFocusMinute/5;
										currentMinuteArray = populateStateLookupArrays("mts");
									break;
								case "fourthColumn":
										switch(inFocusAMPM){
											case "PM":
												if((8 + tempDispY) < 7){
													inFocusAMPM = "AM";
													tempColDivY = -195+39;
												}
												else
													tempColDivY = -195;
												break;
											case "AM":
												if((8 + tempDispY) > 7){
													inFocusAMPM = "PM";
													tempColDivY = -195-39;
												}
												else
													tempColDivY = -195;
												break;
										}
										currentAMPMArray = populateStateLookupArrays("amp");
									break;
							}
							// animate the column
								$(activeColumn).animate({'top' : tempColDivY+"px"}, 500, function(){
									// upon end of animation, swap the old column with new column
									$('#'+fullId+' .innerDivJSDTPV').remove('.'+currentActiveData.column+'JSDTPV');
									$('#'+fullId+' .innerDivJSDTPV').append(toAddDiv);
									$('#'+fullId+' .innerDivJSDTPV .'+currentActiveData.column+'JSDTPV').css("top", "-195px");
									// populate the data into the new column with new inFocus values
									populateRowData(currentActiveData.column);
									if(tempDispY == -1)
										setIblocProperty(false);
									else
										setIblocProperty(true);
								});
							// clear all the flags so that a new action can begin
							mouseMoveFlag = false;
							mouseDownFlag = false;
							activeColumn = null;
					}
					else{ // --------------------------------------------------- this section handles the click
							// determine the offset of the new inFocus value
							var divOffset = $('#'+fullId+' .innerDivJSDTPV').offset().top;
							var mouseYPosition = e.pageY - divOffset;
							var addToFocus = parseInt(mouseYPosition/rowHeight, 10) - 2;
							var tempYPos = -195 - (addToFocus*rowHeight);
							// populate the new column
							var toAddDiv = populateColumns(currentActiveData.column).theDiv;						
							// set the inFocus values to new values and re-populate the current active arrays
							switch(currentActiveData.column){
								case "firstColumn":
										var tempDate = new Date(inFocusYear, inFocusMonth, inFocusDate, inFocus24Hour, inFocusMinute, 0);
										tempDate = new Date(tempDate.getTime() +  addToFocus*millisecondsPerDay);
										inFocusYear = tempDate.getFullYear();
										inFocusMonth = tempDate.getMonth();
										inFocusDate = tempDate.getDate();
										inFocusDay = tempDate.getDay();
										currentDmdArray = populateStateLookupArrays("dmd");
									break;
								case "secondColumn":
										inFocusHour = parseInt(currentActiveData.activeArray[8 + (addToFocus-1)], 10);
										if(inFocusHour != 12)
											inFocus24Hour = (inFocusAMPM == "AM")? inFocusHour : inFocusHour + 12;
										else
											inFocus24Hour = (inFocusAMPM == "AM")? 0 : inFocusHour;
										currentHourArray = populateStateLookupArrays("hrs");
									break;
								case "thirdColumn":
										inFocusMinute = parseInt(currentActiveData.activeArray[8 + (addToFocus-1)], 10);
										inFocusMinuteIndex = inFocusMinute/5;
										currentMinuteArray = populateStateLookupArrays("mts");
									break;
								case "fourthColumn":
									switch(inFocusAMPM){
										case "AM":
											if((8 + (addToFocus-1)) == 8){
												inFocusAMPM = "PM";
												tempYPos = -195-39;
											}
											else
												tempYPos = -195;
											break;
										case "PM":
											if((8 + (addToFocus-1)) == 6){
												inFocusAMPM = "AM";
												tempYPos = -195+39;
											}
											else
												tempYPos = -195;
											break;
									}
									currentAMPMArray = populateStateLookupArrays("amp");
								break;
							}
							// animate the column
							if(tempYPos != -195){
								$(activeColumn).animate({'top' : tempYPos}, 500, function(){
									// upon end of animation, swap the old column with new column
									$('#'+fullId+' .innerDivJSDTPV').remove('.'+currentActiveData.column+'JSDTPV');
									$('#'+fullId+' .innerDivJSDTPV').append(toAddDiv);
									$('#'+fullId+' .innerDivJSDTPV .'+currentActiveData.column+'JSDTPV').css("top", "-195px");
									// populate the data into the new column with new inFocus values
									populateRowData(currentActiveData.column);
									if(tempYPos == -195)
										setIblocProperty(false);
									else
										setIblocProperty(true);
								});
							}
							// clear all the flags
							mouseDownFlag = false;
							activeColumn = null;
					}
				}
			}
			if(customizeForDevice()){
				gmgWrkArndFrScrlStop = null;
			}
		};
		// call back function for mouse leave
		var mouseLeaveFn = function(){
			if(activeColumn){
				// trigger mouse up
				$(activeColumn).mouseup();
			 }
		};
		
		var bindAllListeners;
		
		bindAllListeners = function (divClass){
				$('#'+fullId+' '+divClass).bind("mouseup",mouseUpFn);
				$('#'+fullId+' '+divClass).bind("mousemove",mouseMoveFn);
				$('#'+fullId+' '+divClass).bind("mousedown",mouseDownFn);
				$('#'+fullId+' '+divClass).bind("mouseleave",mouseLeaveFn);
		};
		
		bindAllListeners(".firstColumnJSDTPV");
		bindAllListeners(".secondColumnJSDTPV");
		bindAllListeners(".thirdColumnJSDTPV");
		bindAllListeners(".fourthColumnJSDTPV");
		
		$('#'+fullId+' .containerDivJSDTPV').bind('mousedown', function(){															
			mouseDownGMGDTPV = true;	// for the onBlur issue in IE when the widget is placed within a view		
			if((inFocusWidgetDTPVJS != null) && (inFocusWidgetDTPVJS != fullId))
				jsiPhoneDTPVInstanceArr[inFocusWidgetDTPVJS.substring(inFocusWidgetDTPVJS.length-4)].sendEvent('onBlur');
			inFocusWidgetDTPVJS = fullId;	
			mouseDownGMGDTPV = false;
		});

		$(document).bind("mousedown", me.blurHandler);
}
catch(e){
	alert("Error setting widget actions: "+e.description);
}

		//--------------------------------------------end widget code -------------------------------------
		
        // correct the offsets appearing for the widget Div
        this.getWidgetDiv().css('lineHeight', 0);
        if($.browser.msie)// for IE
                this.getWidgetDiv().css('marginLeft', 0);
        else if($.browser.opera) // for Opera
                this.getWidgetDiv().css('marginLeft', 0.5);
        else if($.browser.safari) // for Safari
                this.getWidgetDiv().css('marginTop', -5);
		if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
			this.getWidgetDiv().css('marginTop', 0);
}

// 
function validateDateDTPVJS(dateIn, dateFormat){
	
		var monthsArray = new Array(12);
			monthsArray[0] = "January";
			monthsArray[1] = "February";
			monthsArray[2] = "March";
			monthsArray[3] = "April";
			monthsArray[4] = "May";
			monthsArray[5] = "June";
			monthsArray[6] = "July";
			monthsArray[7] = "August";
			monthsArray[8] = "September";
			monthsArray[9] = "October";
			monthsArray[10] = "November";
			monthsArray[11] = "December";
		// look-up table for months
		var monthsShortArray = new Array(12);
			monthsShortArray[0] = "Jan";
			monthsShortArray[1] = "Feb";
			monthsShortArray[2] = "Mar";
			monthsShortArray[3] = "Apr";
			monthsShortArray[4] = "May";
			monthsShortArray[5] = "Jun";
			monthsShortArray[6] = "Jul";
			monthsShortArray[7] = "Aug";
			monthsShortArray[8] = "Sep";
			monthsShortArray[9] = "Oct";
			monthsShortArray[10] = "Nov";
			monthsShortArray[11] = "Dec";
		// look-up table for days
		var weekdaysArray=new Array(7);
			weekdaysArray[0]="Sun";
			weekdaysArray[1]="Mon";
			weekdaysArray[2]="Tue";
			weekdaysArray[3]="Wed";
			weekdaysArray[4]="Thu";
			weekdaysArray[5]="Fri";
			weekdaysArray[6]="Sat";
		// look-up table for minutes
		var minutesArray=new Array(12);
			minutesArray[0]="00";
			minutesArray[1]="05";
			minutesArray[2]="10";
			minutesArray[3]="15";
			minutesArray[4]="20";
			minutesArray[5]="25";
			minutesArray[6]="30";
			minutesArray[7]="35";
			minutesArray[8]="40";
			minutesArray[9]="45";
			minutesArray[10]="50";
			minutesArray[11]="55";
					
		var dateData = new Object();
		var stringArray = dateIn.split(/[ :\/]/);
		if(stringArray.length != 6){
			dateData.isCorrect = false;
			return dateData;
		}

		else if(parseInt(stringArray[3], 10) < 0 || parseInt(stringArray[3], 10) > 12){
			dateData.isCorrect = false;
			return dateData;
		}
		else if(parseInt(stringArray[4], 10) < 0 || parseInt(stringArray[4], 10) > 59){
			dateData.isCorrect = false;
			return dateData;
		}
		else if(!((stringArray[5]) == "AM" || (stringArray[5]) == "PM")){
			dateData.isCorrect = false;
			return dateData;
		}
		else{
			var tempMinute = parseInt(stringArray[4], 10);
			tempMinute = tempMinute - (tempMinute % 5);
			
			dateData.ampm = stringArray[5];
			dateData.minute = tempMinute;
			dateData.hour = parseInt(stringArray[3], 10);
			
			switch(dateFormat){
				case "DD/MM/YY HH:MM PM":
					if(parseInt(stringArray[0], 10) < 1 || parseInt(stringArray[0], 10) > 31){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(((stringArray[1]).length > 2) || parseInt(stringArray[1], 10) < 1 || parseInt(stringArray[1], 10) > 12){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(((stringArray[2]).length != 2) || parseInt(stringArray[2], 10) < 0 || parseInt(stringArray[2], 10) > 99){
						dateData.isCorrect = false;
						return dateData;
					}
					else{
						dateData.year = "20"+stringArray[2];
						dateData.month = parseInt(stringArray[1], 10) - 1;
						dateData.date = parseInt(stringArray[0], 10);
						dateData.isCorrect = true;
					}
					break;
				case "Year Month Date HH:MM PM":
					if(((stringArray[0]).length != 4) || parseInt(stringArray[0], 10) < 0 || parseInt(stringArray[0], 10) > 9999){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(jQuery.inArray(stringArray[1], monthsArray) == -1){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(parseInt(stringArray[2], 10) < 1 || parseInt(stringArray[2], 10) > 31){
						dateData.isCorrect = false;
						return dateData;
					}
					else{
						dateData.year = parseInt(stringArray[0], 10);
						dateData.month = jQuery.inArray(stringArray[1], monthsArray);
						dateData.date = parseInt(stringArray[2], 10);
						dateData.isCorrect = true;
					}
					break;
				case "MM/DD/YYYY HH:MM PM":
					if(((stringArray[0]).length > 2) || parseInt(stringArray[0], 10) < 1 || parseInt(stringArray[0], 10) > 12){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(parseInt(stringArray[1], 10) < 1 || parseInt(stringArray[1], 10) > 31){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(((stringArray[2]).length != 4) || parseInt(stringArray[2], 10) < 0 || parseInt(stringArray[2], 10) > 9999){
						dateData.isCorrect = false;
						return dateData;
					}
					else{
						dateData.year = parseInt(stringArray[2], 10);
						dateData.month = parseInt(stringArray[0], 10) - 1;
						dateData.date = parseInt(stringArray[1], 10);
						dateData.isCorrect = true;
					}
					break;
				case "MM/DD/YY HH:MM PM":
					if(((stringArray[0]).length > 2) || parseInt(stringArray[0], 10) < 1 || parseInt(stringArray[0], 10) > 12){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(parseInt(stringArray[1], 10) < 1 || parseInt(stringArray[1], 10) > 31){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(((stringArray[2]).length != 2) || parseInt(stringArray[2], 10) < 0 || parseInt(stringArray[2], 10) > 99){
						dateData.isCorrect = false;
						return dateData;
					}
					else{
						dateData.year = "20"+stringArray[2];
						dateData.month = parseInt(stringArray[0], 10) - 1;
						dateData.date = parseInt(stringArray[1], 10);
						dateData.isCorrect = true;
					}
					break;
				case "Mon Date Year HH:MM PM":
					if((stringArray[0]).length != 3 || jQuery.inArray(stringArray[0], monthsShortArray) == -1){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(parseInt(stringArray[1], 10) < 1 || parseInt(stringArray[1], 10) > 31){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(((stringArray[2]).length != 4) || parseInt(stringArray[2], 10) < 0 || parseInt(stringArray[2], 10) > 9999){
						dateData.isCorrect = false;
						return dateData;
					}
					else{
						dateData.year = parseInt(stringArray[2], 10);
						dateData.month = jQuery.inArray(stringArray[0], monthsShortArray);
						dateData.date = parseInt(stringArray[1], 10);
						dateData.isCorrect = true;
					}
					break;
				case "DD/MM/YYYY HH:MM PM":
					if(parseInt(stringArray[0], 10) < 1 || parseInt(stringArray[0], 10) > 31){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(((stringArray[1]).length > 2) || parseInt(stringArray[1], 10) < 1 || parseInt(stringArray[1], 10) > 12){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(((stringArray[2]).length != 4) || parseInt(stringArray[2], 10) < 0 || parseInt(stringArray[2], 10) > 9999){
						dateData.isCorrect = false;
						return dateData;
					}
					else{
						dateData.year = parseInt(stringArray[2], 10);
						dateData.month = parseInt(stringArray[1], 10) - 1;
						dateData.date = parseInt(stringArray[0], 10);
						dateData.isCorrect = true;
					}
					break;
				default:
					if((stringArray[1]).length != 3 || jQuery.inArray(stringArray[1], monthsShortArray) == -1){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(parseInt(stringArray[2], 10) < 1 || parseInt(stringArray[1], 10) > 31){
						dateData.isCorrect = false;
						return dateData;
					}
					else if(jQuery.inArray(stringArray[0], weekdaysArray) == -1){
						dateData.isCorrect = false;
						return dateData;
					}
					else{
						dateData.day = jQuery.inArray(stringArray[0], weekdaysArray);
						dateData.month = jQuery.inArray(stringArray[1], monthsShortArray);
						dateData.date = parseInt(stringArray[2], 10);
						dateData.isCorrect = true;
					}
					break;
			}
			return dateData;
		}
}
// integration with the setValue action widget
irise.iPhoneDateTimePickerVertical.prototype.setValue = function(c){
	var tempVal;
	if($.isArray(c))
		tempVal = c[0];
	else
		tempVal = c;
	var validDate = validateDateDTPVJS(tempVal, this.getProperty('dpDataFormat'));
	if(validDate.isCorrect){
		this.setProperty('dpSelectedDate', tempVal);
		$(this.getWidgetDiv()).children().remove();
		this.onload();
	}
}
//Fires when focus gets loses
function fireiPhoneDTPVJSOnBlur(){
       // jsiPhoneDPPInstanceArr[inFocusWidgetDPVFS].sendEvent('onBlur');
}

irise.iPhoneDateTimePickerVertical.prototype.touchHandler = function(event){
    var touches = event.changedTouches,
        first = touches[0],
        type = "";
         switch(event.type)
    {
        case "touchstart": type = "mousedown"; break;
        case "touchmove":  type="mousemove"; break;        
        case "touchend":   type="mouseup"; break;
        default: return;
    }
             //initMouseEvent(type, canBubble, cancelable, view, clickCount, 
    //           screenX, screenY, clientX, clientY, ctrlKey, 
    //           altKey, shiftKey, metaKey, button, relatedTarget);
    
    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                              first.screenX, first.screenY, 
                              first.clientX, first.clientY, false, 
                              false, false, false, 0/*left*/, null);
	
	gmgWrkArndFrScrlStop = event;
	
    first.target.dispatchEvent(simulatedEvent);
    //event.preventDefault();
}

irise.iPhoneDateTimePickerVertical.prototype.blurHandler = function(event){
	if (inFocusWidgetDTPVJS && !(onBlurGMGChildFinder(event.target, '#'+inFocusWidgetDTPVJS))){
		jsiPhoneDTPVInstanceArr[inFocusWidgetDTPVJS.substring(inFocusWidgetDTPVJS.length-4)].sendEvent('onBlur');
		inFocusWidgetDTPVJS = null;
	}
}

function onBlurGMGChildFinder(childObj, parentName){
	var parentz = $(childObj).parents().get();
	for ( j = 0; j < parentz.length; j++ ) {
		if ( $(parentz[j]).is(parentName) ) {
			return true;
		}
    }
		return false;
}
