var TLUtils = (function () {
	
	function addTravellerChildAges() {
		$(".dtaTripChildren").each(function() {
			var $this = $(this);
			if($this.data("year")) {
				$this[0].value = $this.data("year");
			} else if($this.data("month") != undefined) {			
				$this[0].selectedIndex = $this.data("month"); 
			} else if($this.data("day") != undefined) {
				$this[0].selectedIndex = $this.data("day"); 
			} 			
			$this.selectmenu("refresh");
		});		
	}
	
    function activateChildAge() {
    	//The number of children menus that need to be
    	//remembered if an error occurs or something.
    	try {
    		$(".dtaTripChildren").each(function() {
    			//var rowid = $(this).data("rowid");    			
    			var childrenmenu = $(this); //$('select#TRIP_CHILDREN');
            	childrenmenu[0].selectedIndex = childrenmenu.data('children');
            	childrenmenu.selectmenu("refresh");            	
    		});    					
		} catch (e) {
			// error in setting the number of children
			//alert("Couldnt set the right number of children menu");
		}    	
    	
		//Set the new onChange function for the select menus
        $('.dtaTripChildren').change(function(e) {
            var rowid = $(this).attr('data-rowid');
            var childCount = $(this).val();
            $(this).attr('data-children', childCount);
            
            displayChildAgeDropDowns(rowid, childCount, null);
        });            
    	
        // Setup the page with correct count of populated dropdowns.
        //The dtaRawChildAge are the hidden input fields in tripTraveller 
        //and quick search. 
        $(".dtaRawChildAge").each(function() {
            // Clear legacy example text. TODO stop populating with example and remove this workaround.
            if ($(this).val() == $(this).attr('data-example-text')) {
                $(this).val("");
            }
            
            var rowid = $(this).attr("data-rowid");
            var rawChildAge = $('.dtaRawChildAge' + rowid).val();  
            //alert(rowid + " " + rawChildAge);
            if (rawChildAge != "" && rawChildAge != null) {
                var rawChildAgeArray = rawChildAge.split(',');
                var childCount = $(".dtaTripChildren" + rowid).val(rawChildAgeArray.length);
                //TODO remove data-children attr and use the rawChildAgeArray.length only
                var childCount = $(".dtaTripChildren" + rowid).attr('data-children');                                
                displayChildAgeDropDowns(rowid, childCount, rawChildAgeArray);
            }
        });
    }   

    function displayChildAgeDropDowns(rowid, childCount, childAgesArray) {
    	$('#dtaTripChildrenAgeDynamic' + rowid).empty();  
    	try {
    		var selectboxes = ChildDD.drawDDs(childCount, childAgesArray, rowid);    		
    	} catch (e) {
    	}
    	    	
    	//$('#dtaTripChildrenAgeDynamic' + rowid).append(selectboxes).trigger("create");
    	
    	
//    	var childCount = $('.dtaTripChildren' + rowid).val();    	
//    	
//    	for(var i=0; i< childCount; i++) {
//    		var options = $('#dtaTripChildrenAgeTemplate').children().clone();
//	        var newSelect = options.find('.dtaTripChildrenAgeDD');  
//	        var label = options.find('label');
//	        label.attr('for', label.attr('for') + (i+1) + "_" + rowid);
//	        newSelect.attr('name', newSelect.attr('name') + (i + 1) + "_" + rowid);
//	        newSelect.attr('id', newSelect.attr('id') + (i + 1) + "_" + rowid);
//	        newSelect.attr('data-rowid', rowid);
//	        newSelect.attr('data-role', '');// TRICK to stop the .trigger(create) creating double enhancements.
//	        newSelect.attr('tabindex', parseInt($('.dtaTripChildren' + rowid).attr('tabindex')) + i);
//	        newSelect.val(23);
//    		//options.triqgger("create");//appendTo($("#dtaTripChildrenAgeDynamic1"));
//    		//options.appendTo($("#dtaTripChildrenAgeDynamic1"));
//    		options.appendTo('body');
//    	}
//    	$(".bgBody").trigger("refresh");
    	
    	
//        $('#dtaTripChildrenAgeDynamic' + rowid).empty();
//        var childCount = $('.dtaTripChildren' + rowid).val();
//        var childCountArr = $('.dtaRawChildAge' + rowid).val().split(',');
//        for (var i = 0; i < childCount; i++) {
//            var newSelectDiv = $('#dtaTripChildrenAgeTemplate').children().clone();
//            var newSelect = newSelectDiv.find('.dtaTripChildrenAgeDD');         
//            newSelect.attr('name', newSelect.attr('name') + (i + 1) + "_" + rowid);
//            newSelect.attr('id', newSelect.attr('id') + (i + 1) + "_" + rowid);
//            newSelect.attr('data-rowid', rowid);
//            newSelect.attr('data-role', '');// TRICK to stop the .trigger(create) creating double enhancements.
//            newSelect.attr('tabindex', parseInt($('.dtaTripChildren' + rowid).attr('tabindex')) + i);
//            newSelect.val(childCountArr[i]);
//       //     newSelectDiv.page();
//            newSelectDiv.trigger("create").appendTo('#dtaTripChildrenAgeDynamic' + rowid).trigger("create");            
//            
//        //      newSelect.appendTo(".ui-page").trigger( "create" );
////              newSelectDiv.appendTo($('#dtaTripChildrenAgeDynamic'+rowid));
//             //  http://jquerymobiledictionary.dyndns.org/faq.html
//           //     newSelectDiv.page();
////                newSelect.selectmenu("refresh",true);
//           // $('#dtaTripChildrenAgeDynamic').children().each(function(){this.name=abc;alert(this.name);})
//        }      
//        TLUtils.refreshMobileForm();
    }


    //Populates the HIDDEN fields from the dropdowns.
    function populateTripChildAgesFromDD() {
        var tripChildAgesString = "";
        // For each DD found, with class x, populate the ,, list for that rowid.
        $('.dtaRawChildAge').each(function() {
            $(this).val(''); // Clear out all hidden fields.
        });
        $('.dtaTripChildrenAgeDD').each(function () {
            var rowid = $(this).attr("data-rowid");
            if (rowid != 'template') {
                var existingString = $(".dtaRawChildAge" + rowid).val();
                if ($(this).val()) {
                    $(".dtaRawChildAge" + rowid).val($(this).val() + ',' + existingString);
                }
            }
        })
        $('.dtaRawChildAge').each(function() {
            var val = this.value;
            $(this).val(val.replace(/,$/g, '')); // Tidy up any trailing commas.
        });
    }

    function setupMobileToggle() {
        $('.dtaRenderAsDesktop').click(function(e) {
            e.preventDefault();
            var strHref = window.location.href;
            if (strHref.indexOf("apptype=desktop") > -1) {
                // Do nothing
            } else if (strHref.indexOf("apptype=mobile") > -1) {
                strHref = strHref.replace("apptype=mobile", "apptype=desktop");
            } else if (strHref.indexOf("?") > -1) {
                strHref = strHref.replace("?", "?apptype=desktop&");
            } else {
                strHref = strHref + "?apptype=desktop&";
            }
            window.location.href = strHref;
        })
        $('.dtaRenderAsMobile').click(function(e) {
            e.preventDefault();
            var strHref = window.location.href;
            if (strHref.indexOf("apptype=mobile") > -1) {
                // Do nothing
            } else if (strHref.indexOf("apptype=desktop") > -1) {
                strHref = strHref.replace("apptype=desktop", "apptype=mobile");
            } else if (strHref.indexOf("?") > -1) {
                strHref = strHref.replace("?", "?apptype=mobile&");
            } else {
                strHref = strHref + "?apptype=mobile";
            }
            window.location.href = strHref;
        })
    }

    function activateSearchFlightTypeRadios() {
        // Have issues with the JQM-b1 handling of the click and vclick on non-<A> elements.
        // Here for example, we have a radio button with a useful onclick event. This, was disabled
        // by JQM. So onchange was used instead. This however failed in IE which waits until onblur to
        // trigger onchange.
        //http://jsfiddle.net/wWFGf/10/
        //https://github.com/jquery/jquery-mobile/issues/1011

        $("[name=dtaSearchdivFlightType]").bind('click change', function() {
            changeTypeOfFlight($('input[name=dtaSearchdivFlightType]:checked').val());
//            $('label').css("min-height", "0px");   //   Resolved jqm beta issue with page height and checked label radio buttons.
        });
    }

    function isMobileClientJS() {
        return $('body[data-apptype="mobile"]').size() > 0;
    }

    function refreshMobileForm() {
        if (TLUtils.isMobileClientJS()) {
            try {
                $("input[type=checkbox]").checkboxradio("refresh");   // Sync all JQM generated checkbox images to the underlying Form state.
            } catch (e) {  // Ignore error : "cannot call methods on checkboxradio prior to initialization; attempted to call method 'refresh'"
            }
            try {
                $("input[type=radio]").checkboxradio("refresh");   // Sync all JQM generated checkbox images to the underlying Form state.
            } catch (e) { // Ignore error
            }
            try {           
                $("select").selectmenu("refresh",true); // Sync all JQM generated select boxes to the underlying Form state.
            } catch (e) {  // Ignore error
            }
        }
    }

    return {
    	addTravellerChildAges:addTravellerChildAges,
        activateChildAge:activateChildAge,        
        displayChildAgeDropDowns:displayChildAgeDropDowns,
        refreshMobileForm:refreshMobileForm,
        isMobileClientJS:isMobileClientJS,
        activateSearchFlightTypeRadios:activateSearchFlightTypeRadios,
        setupMobileToggle:setupMobileToggle,
        populateTripChildAgesFromDD:populateTripChildAgesFromDD
    };
})();
