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

var jsiPhoneDPPObjArr = new Array(); // data for all instances of the Flex component
var iPhoneDPVJSInstanceArr = new Array(); // reference to all instances of the Flex component
var jsiPhoneDPPKey = 0; // holds the id of the instance being loaded
var inFocusWidgetDPVJS;
var gmgWrkArndFrScrlStop;
var mouseDownGMGDPV;
irise.iPhoneDatePickerVertical = function(){
}

irise.iPhoneDatePickerVertical.prototype.onload = function(){
        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);
        jsiPhoneDPPKey = 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 
		iPhoneDPVJSInstanceArr[jsiPhoneDPPKey] = this;   // store the current instance of the widget
		
		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;
		}
		
		var datePickerPObject = {};
		// look-up table for months
		var monthsArray = new Array();
			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";
		// 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();
		// object that stores the data to be sent to the flex object
		// retrieve the widget properties
		try{
		var displayFormat;
		var dPickerOptions =  this.getProperty('dpOptions');
		if(dPickerOptions === "Date (Month Date Year)" || dPickerOptions === null || dPickerOptions === "undefined" || dPickerOptions === ""){
				displayFormat = "MDY";
		}
		else{
				displayFormat = "YMD";
		}
		var dPickerDataFormat = this.getProperty('dpDataFormat');
		if(dPickerDataFormat == null || dPickerDataFormat == "undefined" || dPickerDataFormat == ""){
				dPickerDataFormat = "Month Date Year";
		}
		var dPickerSelDate = this.getProperty('dpSelectedDate');
		if(dPickerSelDate == "" || dPickerSelDate == null || dPickerSelDate == "undefined"){
				dPickerSelDate = "";
		}
		else{
			var validDate = validateDateDPVJS(dPickerSelDate, dPickerDataFormat);
			if(validDate.isCorrect){
				inFocusMonth = validDate.month;
				inFocusDate = validDate.date;
				inFocusYear = parseInt(validDate.year, 10);
				//alert(validDate.year);
			}
		}
		var dPickerTagertWidget = this.getProperty('dpTargtWidget');
		if(dPickerTagertWidget == "" || dPickerTagertWidget == null || dPickerTagertWidget == "undefined"){
						dPickerTagertWidget = "";       // no need to check the autoshow field
		}
		else{
		}
		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';
		// populate the object with data
		datePickerPObject = {
				'dateDisplayFormat' : dPickerOptions,
				'selectedDate' : dPickerSelDate,
				'datePickerDateFormat' : dPickerDataFormat,
				'datePickerFontFamily' : dPickerFontFamily,
				'datePickerFontSize' : dPickerFontSize,
				'datePickerFontColor' : dPickerFontColor,
				'datePickerFontWeight' : dPickerFontWeight
		};
		// individualize the data for each instance of the flex component on the page
		jsiPhoneDPPObjArr[jsiPhoneDPPKey] = datePickerPObject;
		
		}
		catch(e){
			alert("error retrieving widget properties: "+e.description);	
		}
		
		try{
		// 
		function setiPhoneDPPJSProperties(vlue, fireEvent){
			me.setProperty('dpSelectedDate',vlue);  // sets the widget property
			datePickerPObject.selectedDate = 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 err = false;
				switch(monthsArray[inFocusMonth]){
					case "April":
					case "June":
					case "September":
					case "November":
						if(inFocusDate > 30){
							err = true;
						}
						break;
					case "February":
						if(inFocusDate > 28){
							if(inFocusDate > 29){
								err = true;
							}
							else if(inFocusDate == 29){
								if(inFocusYear % 4 != 0){
									err = true;
								}
							}
						}
						break;
				}
				if(!err){
					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 = monthsArray[inFocusMonth].substr(0, 3);
					switch(dPickerDataFormat){
						case "Year, Month, Date":
							tempDateStr = inFocusYear.toString()+", "+monthsArray[inFocusMonth]+", "+inFocusDate.toString();
							break;
						case "MM/DD/YYYY":
							tempDateStr = tempMonth+"/"+inFocusDate.toString()+"/"+inFocusYear.toString();
							break;
						case "MM/DD/YY":
							tempDateStr = tempMonth+"/"+inFocusDate.toString()+"/"+halfYear;
							break;
						case "Mon Date Year":
							tempDateStr = halfMonth+" "+inFocusDate.toString()+" "+inFocusYear.toString();
							break;
						case "DD/MM/YYYY":
							tempDateStr = inFocusDate.toString()+"/"+tempMonth+"/"+inFocusYear.toString();
							break;
						case "DD/MM/YY":
							tempDateStr = inFocusDate.toString()+"/"+tempMonth+"/"+halfYear;
							break;
						default:
							//alert(inFocusYear);
							tempDateStr = monthsArray[inFocusMonth]+" "+inFocusDate.toString()+" "+inFocusYear.toString();
							break;
					}
					setiPhoneDPPJSProperties(tempDateStr, fireEvent);
				}
				else
					alert("Invalid date!");
			}
		}
		catch(e){
			alert("error setting iBloc 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 "y": // year 
						inFocusElement = inFocusYear;
						startingElement = inFocusElement - 7;
						if(isNaN(startingElement)){
							startingElement = 2003;
						}
						for(i = 0; i < 15; i++){
							finalArray[i] = startingElement;
							startingElement++;
						}
					break;
				case "m": // month
						tempArray = monthsArray;
						inFocusElement = inFocusMonth;
						startingElement = inFocusElement - 7;
						if(startingElement < 0){
							startingElement = monthsArray.length + startingElement;
						}
						else if(isNaN(startingElement)){
							startingElement = 1;
						}
						for(i = 0; i < 15; i++){
							if(startingElement > (tempArray.length - 1))
								startingElement = 0;
							finalArray[i] = tempArray[startingElement];
							startingElement++;
						}
					break;
				case "d": // date
						inFocusElement = inFocusDate;
						startingElement = inFocusElement - 7;
						if(startingElement < 1){
							startingElement = 31 + startingElement;
						}
						else if(isNaN(startingElement)){
							startingElement = 1;
						}
						for(i = 0; i < 15; i++){
							if(startingElement > 31)
								startingElement = 1;
							finalArray[i] = startingElement;
							startingElement++;
						}
					break;
			}
			return finalArray;
		};
		//the current state look-up arrays
		var currentYearArray = populateStateLookupArrays("y");
		var currentMonthArray = populateStateLookupArrays("m");
		var currentDateArray = populateStateLookupArrays("d");

		$('<div class="containerDivJSDPV dpvContainerDiv" id="'+fullId+'"><div class="innerDivJSDPV"></div></div>').appendTo('#'+fullId);
		// apply the appropriate background image
		$('#'+fullId+' .containerDivJSDPV').addClass((displayFormat == "YMD")? 'containerDivBgYMD':'containerDivBgMDY');
		// utility function to populate the inner div with columns and rows within
		function populateColumns(divClass){
			var toAddDiv;
			var rowDivs = "";
			if(displayFormat == "YMD"){
				if(divClass == "secondColumn"){
					for(i = 0; i < 15; i++){
						rowDivs = rowDivs + '<div class = "rowDivJSDPV" style="width: 93%; text-align: right;"></div>';
					}
				}
				else{
					for(i = 0; i < 15; i++){
						rowDivs = rowDivs + '<div class = "rowDivJSDPV"></div>';
					}
				}
				toAddDiv = '<div class="ui-widget-content-JSDPV '+divClass+'JSDPV">'+rowDivs+'</div>';
			}
			else{
				// the widget was intially built with the YMD format and hence the classes in css reflect that.
				switch(divClass){
					case "firstColumn": // the first column in MDY is the months column which has a class secondColumnJSPDV 
						for(i = 0; i < 15; i++){
							rowDivs = rowDivs + '<div class = "rowDivJSDPV" style="width: 93%; text-align: right;"></div>';
						}
						toAddDiv = '<div class="ui-widget-content-JSDPV secondColumnJSDPV">'+rowDivs+'</div>';
						break;
					case "secondColumn": // the Date column
						for(i = 0; i < 15; i++){
							rowDivs = rowDivs + '<div class = "rowDivJSDPV"></div>';
						}
						toAddDiv = '<div class="ui-widget-content-JSDPV thirdColumnJSDPV">'+rowDivs+'</div>';
						break;
					case "thirdColumn": // the year column
						for(i = 0; i < 15; i++){
							rowDivs = rowDivs + '<div class = "rowDivJSDPV"></div>';
						}
						toAddDiv = '<div class="ui-widget-content-JSDPV firstColumnJSDPV">'+rowDivs+'</div>';
						break;
				}
			}
			var divObj = { 'theDiv' : toAddDiv, 'theColumn' : divClass};
			return divObj;
		}
		// append the populated divs to the page
		$('#'+fullId+' .innerDivJSDPV').append(populateColumns("firstColumn").theDiv);
		$('#'+fullId+' .innerDivJSDPV').append('<div class="spacerDivJSDPV"></div>');
		$('#'+fullId+' .innerDivJSDPV').append(populateColumns("secondColumn").theDiv);
		$('#'+fullId+' .innerDivJSDPV').append('<div class="spacerDivJSDPV"></div>');
		$('#'+fullId+' .innerDivJSDPV').append(populateColumns("thirdColumn").theDiv);
		
		// utility function to populate the data for each row
		function populateRowData(str){
			var childrenArray;
			var tempCurrentArray;
			if(displayFormat == "YMD"){
				childrenArray = $('#'+fullId+' .innerDivJSDPV .'+str+'JSDPV').children();
				switch(str){
					case "firstColumn":
						tempCurrentArray = currentYearArray;
						break;
					case "secondColumn":
						tempCurrentArray = currentMonthArray;
						break;
					case "thirdColumn":
						tempCurrentArray = currentDateArray;
						break;
				}
			}
			else{
				switch(str){
					case "firstColumn":
						childrenArray = $('#'+fullId+' .innerDivJSDPV .secondColumnJSDPV').children();
						tempCurrentArray = currentMonthArray;
						break;
					case "secondColumn":
						childrenArray = $('#'+fullId+' .innerDivJSDPV .thirdColumnJSDPV').children();
						tempCurrentArray = currentDateArray;
						break;
					case "thirdColumn":
						childrenArray = $('#'+fullId+' .innerDivJSDPV .firstColumnJSDPV').children();
						tempCurrentArray = currentYearArray;
						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");
		
		setIblocProperty(false);
		// make the columns draggable
		$(function() {
			$( '#'+fullId+' .ui-widget-content-JSDPV' ).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 currentActiveArray = {}; // info about current active element
		// callback function for mouse down
		var mouseDownFn = function(e){
			if(customizeForDevice()){
				gmgWrkArndFrScrlStop.preventDefault();
			}
			mouseDownFlag = true;
			activeColumn = this;
			notAlreadyRun = true;
			alertLeaved = ": ";
			if($(activeColumn).is('.firstColumnJSDPV')){
				if(displayFormat == "YMD")
					currentActiveData = {'activeArray': currentYearArray, 'column': "firstColumn", 'realColumn': "firstColumnJSDPV"};
				else
					currentActiveData = {'activeArray': currentYearArray, 'column': "thirdColumn", 'realColumn': "firstColumnJSDPV"};
				}
			else if($(activeColumn).is('.secondColumnJSDPV')){
				if(displayFormat == "YMD")
					currentActiveData = {'activeArray': currentMonthArray, 'column': "secondColumn", 'realColumn': "secondColumnJSDPV"};
				else
					currentActiveData = {'activeArray': currentMonthArray, 'column': "firstColumn", 'realColumn': "secondColumnJSDPV"};
				}
			else{
				if(displayFormat == "YMD")
					currentActiveData = {'activeArray': currentDateArray, 'column': "thirdColumn", 'realColumn': "thirdColumnJSDPV"};
				else
					currentActiveData = {'activeArray': currentDateArray, 'column': "secondColumn", 'realColumn': "thirdColumnJSDPV"};
				}
			if(customizeForDevice()){
				gmgWrkArndFrScrlStop = null;
			}
			if($.browser.msie){// for IE
			if(!mouseDownGMGDPV){
				e.stopPropagation();
				$('#'+fullId+' .dpvContainerDiv').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
						/*unbindAllListeners();
						$( '#'+fullId+' .ui-widget-content-JSDPV' ).draggable("destroy");*/
						// determine the new inFocus value
						var tempColDivY = ($(activeColumn).offset().top - $('#'+fullId+' .innerDivJSDPV').offset().top) - (($(activeColumn).offset().top - $('#'+fullId+' .innerDivJSDPV').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":
								if(displayFormat == "YMD"){
									inFocusYear = inFocusYear + (tempDispY+1);
									currentYearArray = populateStateLookupArrays("y");
								}
								else{
									inFocusMonth = jQuery.inArray(currentActiveData.activeArray[8 + tempDispY], monthsArray);
									currentMonthArray = populateStateLookupArrays("m");
								}
								break;
							case "secondColumn":
								if(displayFormat == "YMD"){
									inFocusMonth = jQuery.inArray(currentActiveData.activeArray[8 + tempDispY], monthsArray);
									currentMonthArray = populateStateLookupArrays("m");
								}
								else{
									inFocusDate = parseInt(currentActiveData.activeArray[8 + tempDispY], 10);
									currentDateArray = populateStateLookupArrays("d");
								}
								break;
							case "thirdColumn":
								if(displayFormat == "YMD"){
									inFocusDate = parseInt(currentActiveData.activeArray[8 + tempDispY], 10);
									currentDateArray = populateStateLookupArrays("d");
								}
								else{
									inFocusYear = inFocusYear + (tempDispY+1);
									currentYearArray = populateStateLookupArrays("y");
								}
								break;
						}
						// animate the column
						$(activeColumn).animate({'top' : tempColDivY}, 500, function(){
							// upon end of animation, swap the old column with new column
							$('#'+fullId+' .innerDivJSDPV').remove('.'+currentActiveData.realColumn);
							$('#'+fullId+' .innerDivJSDPV').append(toAddDiv);
							$('#'+fullId+' .innerDivJSDPV .'+currentActiveData.realColumn).css("top", "-195px");
							// populate the data into the new column with new inFocus values
							populateRowData(currentActiveData.column);
							/*$( '#'+fullId+' .ui-widget-content-JSDPV' ).draggable({ axis: "y" });
							// bind the listeners
							bindAllListeners(".firstColumnJSDPV");
							bindAllListeners(".secondColumnJSDPV");
							bindAllListeners(".thirdColumnJSDPV");*/
							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
						/*unbindAllListeners();
						$( '#'+fullId+' .ui-widget-content-JSDPV' ).draggable("destroy");*/
						// determine the offset of the new inFocus value
						var divOffset = $('#'+fullId+' .innerDivJSDPV').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":
								if(displayFormat == "YMD"){
									inFocusYear = inFocusYear + addToFocus;
									currentYearArray = populateStateLookupArrays("y");
								}
								else{
									inFocusMonth = jQuery.inArray(currentActiveData.activeArray[8 + (addToFocus-1)], monthsArray);
									currentMonthArray = populateStateLookupArrays("m");
								}
								break;
							case "secondColumn":
								if(displayFormat == "YMD"){
									inFocusMonth = jQuery.inArray(currentActiveData.activeArray[8 + (addToFocus-1)], monthsArray);
									currentMonthArray = populateStateLookupArrays("m");
								}
								else{
									inFocusDate = parseInt(currentActiveData.activeArray[8 + (addToFocus-1)], 10);
									currentDateArray = populateStateLookupArrays("d");
								}
								break;
							case "thirdColumn":
								if(displayFormat == "YMD"){
									inFocusDate = parseInt(currentActiveData.activeArray[8 + (addToFocus-1)], 10);
									currentDateArray = populateStateLookupArrays("d");
								}
								else{
									inFocusYear = inFocusYear + addToFocus;
									currentYearArray = populateStateLookupArrays("y");
								}
								break;
						}
						// animate the column
						$(activeColumn).animate({'top' : tempYPos}, 500, function(){
							// upon end of animation, swap the old column with new column
							$('#'+fullId+' .innerDivJSDPV').remove('.'+currentActiveData.realColumn);
							$('#'+fullId+' .innerDivJSDPV').append(toAddDiv);
							$('#'+fullId+' .innerDivJSDPV .'+currentActiveData.realColumn).css("top", "-195px");
							// populate the data into the new column with new inFocus values
							populateRowData(currentActiveData.column);
							/*$( '#'+fullId+' .ui-widget-content-JSDPV' ).draggable({ axis: "y" });
							// bind the listeners
							bindAllListeners(".firstColumnJSDPV");
							bindAllListeners(".secondColumnJSDPV");
							bindAllListeners(".thirdColumnJSDPV");*/
							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();
			 }
		};
		// utility function to bind the events and callbacks for all columns
		function bindAllListeners(divClass){
			$('#'+fullId+' '+divClass).bind("mousemove",mouseMoveFn);
			$('#'+fullId+' '+divClass).bind("mousedown",mouseDownFn);
			$('#'+fullId+' '+divClass).bind("mouseup",mouseUpFn);
			$('#'+fullId+' '+divClass).bind("mouseleave",mouseLeaveFn);
		}
		
		/*function unbindAllListeners(){
			$('#'+fullId+' .firstColumnJSDPV').unbind();
			$('#'+fullId+' .secondColumnJSDPV').unbind();
			$('#'+fullId+' .thirdColumnJSDPV').unbind();
		}*/
		// bind the listeners
		bindAllListeners(".firstColumnJSDPV");
		bindAllListeners(".secondColumnJSDPV");
		bindAllListeners(".thirdColumnJSDPV");
		}
		catch(e){
			alert("error while generating the widget: "+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);
			
			
		//	Adds On BLur Function to Outer Div
		$('#'+fullId+' .dpvContainerDiv').bind('mousedown', function(){
			//if(inFocusWidgetDPVJS && inFocusWidgetDPVJS != fullId.substring(fullId.length-4))
			//	iPhoneDPVJSInstanceArr[inFocusWidgetDPVJS].sendEvent('onBlur');
			//$('#'+fullId+' .dpvContainerDiv').focus();
			mouseDownGMGDPV = true;
			if((inFocusWidgetDPVJS != null) && (inFocusWidgetDPVJS != fullId))
				iPhoneDPVJSInstanceArr[inFocusWidgetDPVJS.substring(inFocusWidgetDPVJS.length-4)].sendEvent('onBlur');
			inFocusWidgetDPVJS = fullId;		
			mouseDownGMGDPV = false;
		});
		
		 //if($.browser.msie){// for IE
		 	$(document).bind("mousedown", me.blurHandler);
		/* }
		 else{
		 	document.addEventListener("mousedown", function(e){
				if (inFocusWidgetDPVJS && !($(e.target).isChildOf('#'+inFocusWidgetDPVJS))){
					iPhoneDPVJSInstanceArr[inFocusWidgetDPVJS.substring(inFocusWidgetDPVJS.length-4)].sendEvent('onBlur');
					inFocusWidgetDPVJS = "";
				}
		 	});
		 }*/
		 	
		
		if (customizeForDevice()){
			document.addEventListener("touchstart", me.touchHandler, true);
			document.addEventListener("touchmove", me.touchHandler, true);
			document.addEventListener("touchend", me.touchHandler, true);
		}
		//On Load Ends Here...
}

// 
function validateDateDPVJS(dateIn, dateFormat){
	
				var monthsArray = new Array();
					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";
					
				var dateData = {};
				var stringArray;
				switch(dateFormat){
					case "Year, Month, Date":
						stringArray = dateIn.split(', ');
						if(stringArray.length != 3){
							dateData.isCorrect = false;
							return dateData;
						}
						else 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 = stringArray[0];
							dateData.month = jQuery.inArray(stringArray[1], monthsArray);
							dateData.date = stringArray[2];
							dateData.isCorrect = true;
							return dateData;
						}
						break;
					case "MM/DD/YYYY":
						stringArray = dateIn.split('/');
						if(stringArray.length != 3){
							dateData.isCorrect = false;
							return dateData;
						}
						else 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 = stringArray[2];
							dateData.month = parseInt(stringArray[0], 10) - 1;
							dateData.date = stringArray[1];
							dateData.isCorrect = true;
							return dateData;
						}
						break;
					case "MM/DD/YY":
						stringArray = dateIn.split('/');
						if(stringArray.length != 3){
							dateData.isCorrect = false;
							return dateData;
						}
						else 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 = stringArray[1];
							dateData.isCorrect = true;
							return dateData;
						}
						break;
					case "Mon Date Year":
						stringArray = dateIn.split(' ');
						if(stringArray.length != 3){
							dateData.isCorrect = false;
							return dateData;
						}
						else if(stringArray[0].length != 3){
							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{
							var found = false;
							var tempId;
							for(i = 0;i < monthsArray.length; i++){
								if(stringArray[0] == monthsArray[i].substr(0,3)){ // check substr fn
									found = true;
									tempId = i;
								}
							}
							if(!found){
								dateData.isCorrect = false;
								return dateData;
							}
							else{
								dateData.year = stringArray[2];
								dateData.month = tempId;
								dateData.date = stringArray[1];
								dateData.isCorrect = true;
								return dateData;
							}
						}
						break;
					case "DD/MM/YYYY":
						stringArray = dateIn.split('/');
						if(stringArray.length != 3){
							dateData.isCorrect = false;
							return dateData;
						}
						else 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 = stringArray[2];
							dateData.month = parseInt(stringArray[1], 10) - 1;
							dateData.date = stringArray[0];
							dateData.isCorrect = true;
							return dateData;
						}
						break;
					case "DD/MM/YY":
						stringArray = dateIn.split('/');
						if(stringArray.length != 3){
							dateData.isCorrect = false;
							return dateData;
						}
						else 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 = stringArray[0];
							dateData.isCorrect = true;
							return dateData;
						}
						break;
					default: // Month Date Year
						stringArray = dateIn.split(' ');
						if(stringArray.length != 3){
							dateData.isCorrect = false;
							return dateData;
						}
						else if((stringArray[2].length != 4) || parseInt(stringArray[0], 10) < 0 || parseInt(stringArray[0], 10) > 9999){
							dateData.isCorrect = false;
							return dateData;
						}
						else if(parseInt(stringArray[1], 10) < 1 || parseInt(stringArray[1], 10) > 31){
							dateData.isCorrect = false;
							return dateData;
						}
						else if(jQuery.inArray(stringArray[0], monthsArray) == -1){
							dateData.isCorrect = false;
							return dateData;
						}
						else{
							dateData.year = stringArray[2];
							dateData.month = jQuery.inArray(stringArray[0], monthsArray);
							dateData.date = stringArray[1];
							dateData.isCorrect = true;
							return dateData;
						}
						break;
				}
			}
// integration with the setValue action widget
irise.iPhoneDatePickerVertical.prototype.setValue = function(c){
	var tempVal;
	if($.isArray(c))
		tempVal = c[0];
	else
		tempVal = c;
	var validDate = validateDateDPVJS(tempVal, this.getProperty('dpDataFormat'));
	if(validDate.isCorrect){
		this.setProperty('dpSelectedDate', tempVal);
		$(this.getWidgetDiv()).children().remove();
		this.onload();
	}
}


irise.iPhoneDatePickerVertical.prototype.touchHandler = function(event){
    var dpvTouches = event.changedTouches,
        dpvFirst = dpvTouches[0],
        dpvType = "";
        switch(event.type)
    	{
			case "touchstart": dpvType = "mousedown"; break;
			case "touchmove":  dpvType="mousemove"; break;        
			case "touchend":   dpvType="mouseup"; break;
			default: return;
    	}

    
		var dpvSimulatedEvent = document.createEvent("MouseEvent");
		dpvSimulatedEvent.initMouseEvent(dpvType, true, true, window, 1, 
								  dpvFirst.screenX, dpvFirst.screenY, 
								  dpvFirst.clientX, dpvFirst.clientY, false, 
								  false, false, false, 0/*left*/, null);
		
		gmgWrkArndFrScrlStop = event;
	
		dpvFirst.target.dispatchEvent(dpvSimulatedEvent);
}

irise.iPhoneDatePickerVertical.prototype.blurHandler = function(event){
	if (inFocusWidgetDPVJS && !(onBlurGMGChildFinder(event.target,'#'+inFocusWidgetDPVJS))){
		iPhoneDPVJSInstanceArr[inFocusWidgetDPVJS.substring(inFocusWidgetDPVJS.length-4)].sendEvent('onBlur');
		inFocusWidgetDPVJS = 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;
}
