irise.namespace("irise"); // sets the namespace
var iPhoneValuePickerVerticalInstanceArr = new Array(); // reference to all instances
var inFocusValue; // value of the in Focus element
var vpvJSMouseMoved = false;
var vpvJSMousePressed = false;
var vpvJSDivGotFocus;
var gmgWrkArndFrScrlStop;
var mouseDownGMGVPV;

irise.iPhoneValuePickerVertical = function(){
}

irise.iPhoneValuePickerVertical.prototype.onload = function(){
	var me=this;
	// shortening large identifiers
	var inFocusValIndexVPV; // Index of the in Focus element
	
	var vpvId = this.getId();
    //vpvId = vpvId.substring(vpvId.length-4);
	iPhoneValuePickerVerticalInstanceArr[vpvId] = this;   // Stores the widget instance in the global array.
		
	var vpvSelectionIndicator = this.getProperty('vpSelectionIndicator');
	
	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 vpvPickerOptions =  this.getProperty('vpOptions');
	if(vpvPickerOptions == "" || vpvPickerOptions == null || vpvPickerOptions == "undefined"){
		vpvPickerOptions = new Array();
		vpvPickerOptions[0] = "Lorem ipsum";
		vpvPickerOptions[1] = "Etiam";
		vpvPickerOptions[2] = "Sed vitae";
		vpvPickerOptions[3] = "Quisque";
		vpvPickerOptions[4] = "Nam porta";
		vpvPickerOptions[5] = "Morbi ornare";
	}
	else{
		if (typeof(vpvPickerOptions) == 'string'){
			var tempvpvPickerOptions = vpvPickerOptions;
			vpvPickerOptions = new Array();
			vpvPickerOptions[0] = tempvpvPickerOptions;
		}
	}
	
	var vpvPickerSelOpt = this.getProperty('vpSelectedOption');
	if(vpvPickerSelOpt == "" || vpvPickerSelOpt == null || vpvPickerSelOpt == "undefined")
		vpvPickerSelOpt = "Sed vitae";
		
	var vpvPickerTagertWidget = this.getProperty('vpTargtWidget');
	if(vpvPickerTagertWidget == "" || vpvPickerTagertWidget == null || vpvPickerTagertWidget == "undefined")
		vpvPickerTagertWidget = "";	// no need to check the autoshow field
		
	var vpvPickerFontFamily = this.getProperty('vpFontFamily');
	
	var vpvPickerFontSize = this.getProperty('vpFontSize');
	if(vpvPickerFontSize == "" || vpvPickerFontSize == null || vpvPickerFontSize == "undefined" || vpvPickerFontSize < 18 || vpvPickerFontSize > 29)
		vpvPickerFontSize = "26";
		
	var vpvPickerFontColor = this.getProperty('vpFontColor');
	if(vpvPickerFontColor == "" || vpvPickerFontColor == null || vpvPickerFontColor == "undefined")
		vpvPickerFontColor = "#000000";
		
	var vpvPickerFontWeight = this.getProperty('vpFontWeight');
	if(vpvPickerFontWeight === null || vpvPickerFontWeight === 'undefined' || vpvPickerFontWeight === false)
		vpvPickerFontWeight = 'normal';
	else
		vpvPickerFontWeight = 'bold';
		
	var vpvCompleteRows = '';
	
	inFocusValIndexVPV = jQuery.inArray(vpvPickerSelOpt, vpvPickerOptions);
	
		
	if (inFocusValIndexVPV  < 0)
		inFocusValIndexVPV = 0;
	
	for(var i = 0; i < vpvPickerOptions.length; i++){
		vpvCompleteRows = vpvCompleteRows + vpvRowPopulator(vpvPickerOptions[i], i, vpvId);
	}
	
	// Checks the picker vpvType
	if (vpvSelectionIndicator === "Check mark")
		var toAppendDiv ='<div class="vpvCheckOuterDiv vpvContainerDiv"><div class="vpvfirstInner"><div class="vpvInnerDiv">'+vpvCompleteRows+'</div></div></div>';
	else
		var toAppendDiv ='<div class="vpvHighlightOuterDiv vpvContainerDiv"><div class="vpvfirstInner"><div class="vpvInnerDiv">'+vpvCompleteRows+'</div></div></div>';
		
	this.getWidgetDiv().append(toAppendDiv);
	// correct the offsets appearing for the widget Div
	this.getWidgetDiv().css('lineHeight', 0);
	if($.browser.msie)// for IE
		this.getWidgetDiv().css('marginTop', 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) // Chrome
		this.getWidgetDiv().css('marginTop', 0);	
	

	//Set the picker text properties
	$('#'+vpvId+' .vpvRowText').css('fontFamily',vpvPickerFontFamily);
	$('#'+vpvId+' .vpvRowText').css('fontSize',vpvPickerFontSize+'px');
	$('#'+vpvId+' .vpvRowText').css('color',vpvPickerFontColor);
	$('#'+vpvId+' .vpvRowText').css('fontWeight',vpvPickerFontWeight);
	
	
	$('#'+vpvId+' .vpvInnerDiv').draggable({ axis: "y" }); // Makes the picker draggable
	
	$('#'+vpvId+' .vpvInnerDiv').animate({ "top" : ((2*39)-(inFocusValIndexVPV*39))+'px'}); // position the Focus Value at centre while loading
		
	$('#'+vpvId+' .vpvInnerDiv').bind('click', function(e) {
		//alert(e.currentTarget);
	});

	$('#'+vpvId+' .vpvInnerDiv').bind('mouseup', function(e) {
		if(customizeForDevice()){
			gmgWrkArndFrScrlStop.preventDefault();
		}
		if (vpvJSMousePressed){
			var oldFocus = inFocusValIndexVPV;
			var fireEvent = false;
			if (!vpvJSMouseMoved){
			//vpvJSMousePressed = false;
			//alert('Moved '+vpvJSMouseMoved);
			//alert('Pressed '+vpvJSMousePressed);
			var offset = $(this).offset();
			var clickedY = e.pageY - offset.top;  // Get the current mouse Y position
			inFocusValIndexVPV = clickedY/39;
			inFocusValIndexVPV = Math.ceil(inFocusValIndexVPV)-1;
			$('#'+vpvId+' .vpvInnerDiv').animate({ "top" : ((2*39)-(inFocusValIndexVPV*39))+'px'}); // position the Focus Value at centre while loading
			
			// Highlight the in Focus Value while clicking on a value
			$('#'+vpvId+' .vpvRowText').css('color',vpvPickerFontColor);
			$('#'+vpvId+' #'+e.target.id).css('color','#324F85');
			
			}

			vpvJSMousePressed = false;
			
			if (vpvJSMouseMoved){
				vpvJSMouseMoved = false;
				var offset = $('#'+vpvId+' .vpvInnerDiv').offset();
				var currentY = e.pageY - offset.top;  // Get the current mouse Y position
				//alert('Moved '+vpvJSMouseMoved);
				//alert('Pressed '+vpvJSMousePressed);
				var pos = $(this).position().top;
				if (pos > 78){
					inFocusValIndexVPV = 0;
					$('#'+vpvId+' .vpvInnerDiv').animate({ "top" : (2*39)+'px'}); // position the Focus Value at centre while loading
				}
				else if (pos <= (-(vpvPickerOptions.length-3)*39)){
					inFocusValIndexVPV = vpvPickerOptions.length-1;
					$('#'+vpvId+' .vpvInnerDiv').animate({ "top" : (-(vpvPickerOptions.length-3)*39)+'px'}); // position the Focus Value at centre while loading
				}
				else{
					var currFocusY = ((2*39)-(inFocusValIndexVPV*39));
					if ( pos < currFocusY ) // If new 'Y' val is less than current Y value
					{
						var diff = pos - currFocusY;
						var noOfElements = Math.round(diff/39);
						inFocusValIndexVPV = inFocusValIndexVPV + Math.abs(noOfElements);
						$('#'+vpvId+' .vpvInnerDiv').animate({ "top" : ((2*39)-(inFocusValIndexVPV*39))+'px'});
					}
					else
					{
						var diff = pos - currFocusY;
						var noOfElements = Math.round(diff/39);
						inFocusValIndexVPV = inFocusValIndexVPV - Math.abs(noOfElements);
						$('#'+vpvId+' .vpvInnerDiv').animate({ "top" : ((2*39)-(inFocusValIndexVPV*39))+'px'});
					}
									
				}
				//inFocusValIndexVPV = clickedY/39;
				//inFocusValIndexVPV = Math.ceil(inFocusValIndexVPV);
				//$('#'+vpvId+' .vpvInnerDiv').animate({ "top" : ((3*39+10)-(inFocusValIndexVPV*39))+'px'}); // position the Focus Value at centre while loading			
				var divChilds = $('#'+vpvId+' .vpvInnerDiv').children();
				var focusDivClass = $(divChilds[inFocusValIndexVPV]).attr('class');
				var textChild = $('#'+vpvId+' .'+focusDivClass).children();
				//$(textChild[0]).attr('id')
				$('#'+vpvId+' .vpvRowText').css('color',vpvPickerFontColor);
				$('#'+vpvId+' #'+$(textChild[inFocusValIndexVPV]).attr('id')).css('color','#324F85');
			}
			
			if (oldFocus != inFocusValIndexVPV)
				fireEvent = true;
			setiPhoneValuePickerVerticalProperties (vpvPickerOptions[inFocusValIndexVPV], fireEvent, vpvId); // sets In Focus value in the target
		}
		
		if(customizeForDevice()){
			gmgWrkArndFrScrlStop = null;
		}
		
	});
	
	$('#'+vpvId+' .vpvInnerDiv').bind('mousemove', function(e) {
		if(customizeForDevice()){
			gmgWrkArndFrScrlStop.preventDefault();
		}
		
		if (vpvJSMousePressed)
			vpvJSMouseMoved = true;
		
		if(customizeForDevice()){
			gmgWrkArndFrScrlStop = null;
		}
	});
	
	$('#'+vpvId+' .vpvInnerDiv').bind('mousedown', function(e) {
		if(customizeForDevice()){
			gmgWrkArndFrScrlStop.preventDefault();
		}
		
		vpvJSMousePressed = 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(!mouseDownGMGVPV){
				e.stopPropagation();
				$('#'+vpvId+' .vpvContainerDiv').mousedown();
			}
		}
	});
	
	$('#'+vpvId+' .vpvInnerDiv').bind('mouseout', function(e) {
		$('#'+vpvId+' .vpvInnerDiv').mouseup();
	});
	
	
	// Handles On Blur Custom Event..
	$('#'+vpvId+' .vpvContainerDiv').bind('mousedown', function(){
			mouseDownGMGVPV = true;													
			if((vpvJSDivGotFocus != null) && (vpvJSDivGotFocus != vpvId))
				iPhoneValuePickerVerticalInstanceArr[vpvJSDivGotFocus].sendEvent('onBlur');
			vpvJSDivGotFocus = vpvId;
			mouseDownGMGVPV = false;	
    });	
	
	$(document).bind("mousedown", me.blurHandler);
	
		
	// Function that sets the selected option in the target widget while widget loading...
	
	iPhoneValuePickerVerticalInstanceArr[vpvId].setProperty('vpSelectedOption',vpvPickerOptions[inFocusValIndexVPV]);	// sets the widget property
	if(iPhoneValuePickerVerticalInstanceArr[vpvId].getProperty('vpTargtWidget')){
		if (iPhoneValuePickerVerticalInstanceArr[vpvId].getProperty('vpTargtWidget').getType() === 'widget') // if an ibloc, then use the setValue acti
			iPhoneValuePickerVerticalInstanceArr[vpvId].getProperty('vpTargtWidget').setValue(vpvPickerOptions[inFocusValIndexVPV]);
		else{ 
			if(iPhoneValuePickerVerticalInstanceArr[vpvId].getProperty('vpTargtWidget').getWidgetDiv().text()){ // if label widget, then use html() method
				iPhoneValuePickerVerticalInstanceArr[vpvId].getProperty('vpTargtWidget').getWidgetDiv().html(vpvPickerOptions[inFocusValIndexVPV]);
				// iPhoneValuePickerVerticalInstanceArr[instanceId].getProperty('vpTargtWidget').getWidgetDiv().show();
			}
			else
				iPhoneValuePickerVerticalInstanceArr[vpvId].getProperty('vpTargtWidget').getWidgetDiv().val(vpvPickerOptions[inFocusValIndexVPV]); // for all others, use the val() method
		}
		//Highlight the selected value
	}
	var divChilds = $('#'+vpvId+' .vpvInnerDiv').children();
	var focusDivClass = $(divChilds[inFocusValIndexVPV]).attr('class');
	var textChild = $('#'+vpvId+' .'+focusDivClass).children();
	$('#'+vpvId+' .vpvRowText').css('color',vpvPickerFontColor);
	$('#'+vpvId+' #'+$(textChild[inFocusValIndexVPV]).attr('id')).css('color','#324F85');
	
	if (customizeForDevice()){
		document.addEventListener("touchstart", me.touchHandler, true);
		document.addEventListener("touchmove", me.touchHandler, true);
		document.addEventListener("touchend", me.touchHandler, true);
	}
	
	
	// on Load End
	
}
// function to set the respective property of JS widget to the corresponding selected value in the flex component
function setiPhoneValuePickerVerticalProperties(vlue, fireEvent, instanceId){
	//alert('Len  :'+iPhoneValuePickerVerticalInstanceArr.length);
	iPhoneValuePickerVerticalInstanceArr[instanceId].setProperty('vpSelectedOption',vlue);	// sets the widget property

if(iPhoneValuePickerVerticalInstanceArr[instanceId].getProperty('vpTargtWidget')){
		if (iPhoneValuePickerVerticalInstanceArr[instanceId].getProperty('vpTargtWidget').getType() === 'widget') // if an ibloc, then use the setValue action
			iPhoneValuePickerVerticalInstanceArr[instanceId].getProperty('vpTargtWidget').setValue(vlue);
		else{ 
			if(iPhoneValuePickerVerticalInstanceArr[instanceId].getProperty('vpTargtWidget').getWidgetDiv().text()){ // if label widget, then use html() method
				iPhoneValuePickerVerticalInstanceArr[instanceId].getProperty('vpTargtWidget').getWidgetDiv().html(vlue);
				// iPhoneValuePickerVerticalInstanceArr[instanceId].getProperty('vpTargtWidget').getWidgetDiv().show();
			}
			else
				iPhoneValuePickerVerticalInstanceArr[instanceId].getProperty('vpTargtWidget').getWidgetDiv().val(vlue); // for all others, use the val() method
		}
	}
	if(fireEvent)
		iPhoneValuePickerVerticalInstanceArr[instanceId].sendEvent('onSelectionChange');
	return "success";
}


// integration with the setValue action widget
irise.iPhoneValuePickerVertical.prototype.setValue = function(c){
	var vpvThisID = this.getId();
	var vpvCurrInFocus = iPhoneValuePickerVerticalInstanceArr[vpvThisID].getProperty('vpSelectedOption')
	var vpvPickerOptions = this.getProperty('vpOptions');
	if ($.isArray(c))
		var newSetVal = c[0];
	else
		var newSetVal = c;
	if (jQuery.inArray(newSetVal, vpvPickerOptions) >= 0 ){
		if (vpvCurrInFocus != newSetVal){
			iPhoneValuePickerVerticalInstanceArr[vpvThisID].sendEvent('onSelectionChange');
			this.setProperty('vpSelectedOption', newSetVal);
			$(this.getWidgetDiv()).children().remove();
			this.onload();
		}
	}
}

function vpvRowPopulator(pickerText, index, vpvDivId){
	var vpvRowDiv = '<div class="vpvRowDiv">';  // Row Div 
	var vpvTextDiv = vpvRowDiv+'<div class="vpvRowText" id="'+vpvDivId+'Div'+index+'" style="width:287px;">'+pickerText+'</div></div>';
	return vpvTextDiv;
}

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

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

irise.iPhoneValuePickerVertical.prototype.blurHandler = function(event){
	if (vpvJSDivGotFocus && !(onBlurGMGChildFinder(event.target,'#'+vpvJSDivGotFocus))){
		iPhoneValuePickerVerticalInstanceArr[vpvJSDivGotFocus].sendEvent('onBlur');
		vpvJSDivGotFocus = 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;
}
