var menuStatus;
var App = {};

Number.prototype.toRad = function() {
	return this * Math.PI / 180;
}

App = {
    splashScreenDuration: 1000,
	initLocation: {lat:37.435937, lon:-122.110601},
	Unit: "KM",
	users : {},
    init: function() {
        
		App.getUsers(false);
		
		App.updateBtnState();

		//var $records = $('#json-records'),
		//myRecords = JSON.parse($records.text());
		var myRecords = [{"date": "Weezer","checkin": "El Scorcho",
		    "checkout": "Weezer",
		    "total": "El Scorcho"
		  } 
		]
		

		$(document).delegate('input[name="daterange"]', "focus", function(){
			$(this).blur();
		});
		
		$('input[name="daterange"]').daterangepicker({ 
			    format: 'YYYY-MM-DD',
			    opens:"left",
			    separator: " to "
			  },
			  function(start, end, label) {
				$("#timesheet_table tbody").html("");
				$.dynatable.settings.dataset.ajaxUrl = 'http://dev.jetcamer.com/babysitter/ws/json.php?getTimeSheet='+ $.dyna_username + "&from=" + start.format('YYYY-MM-DD') + "&to=" + end.format('YYYY-MM-DD');
				$.dynatable.process();
			  }
		);
		


		App.setLoginLogoutLink();

		$(document).delegate(".checkin_checkout", "click", App.checkin_checkout);
		
		$(document).delegate("#manage_user .edit_user", "click", App.edit_user);
		
		$(document).delegate("#timesheetContainer .edit_user", "click", function() {
			$('input[name="daterange"]').val("");
			$("#timesheet_table tbody").html("");
			$('#timesheet_users').hide();
			$('#timesheet').fadeIn(); 
			
			$.dyna_username = $(this).attr("data-username");
			$.dyna_userid 	= $(this).attr("data-userid");
			console.log($.dyna_userid);
			if($.dyna_exist !== true) {
				$.dyna_exist = true;
				$.dynatable = $('#timesheet_table').dynatable({
				  dataset: {
					ajax: true,
					ajaxUrl: 'http://dev.jetcamer.com/babysitter/ws/json.php?getTimeSheet='+ $.dyna_username,
					ajaxOnLoad: true,
					records: []
				  },
				  features: {
					paginate: false,
					recordCount: false,
					sorting: false,
					search: false
				  }
				})
				.bind('dynatable:ajax:success', function(resp, data){
					$("#TotalHours").html(data.TotalHours);
				})
				.data('dynatable');
			}else{
				$.dynatable.settings.dataset.ajaxUrl = 'http://dev.jetcamer.com/babysitter/ws/json.php?getTimeSheet='+ $.dyna_username;
				$.dynatable.process();
			}
		});
		
		$(document).delegate(".get_payment", "click", function() {
			
		});
		
		$(document).delegate("#saveUser", "click", App.save_user);
		$(document).delegate("#delete_user", "click", App.delete_user);
		
		$(document).delegate("#cancelUserEdit", "click", App.setUserList);

		$(document).delegate("#checkin", "click", function(){App.doRequest({action:"checkin"});});
		$(document).delegate("#checkout", "click", function(){App.doRequest({action:"checkout"});});

		$(document).delegate("#payment_rate", "keyup", App.updatePaymentInfo);
		$(document).delegate("#paymentType", "change", App.updatePaymentInfo);
		
		$(document).delegate("#savePaymentBtn", "click", App.savePayment);

		$(document).delegate(".manager", "click", function(){
			if(typeof localStorage.current_user == "undefined") {
				App.doCheckin();
				return;
			}

			var action = eval($(this).attr("data-action"));
			action.call(this);
			$(".listContainer").trigger('create');
		});

		//cancel login process
		$(document).delegate("#checking_cancel", "click", function(){
			localStorage.isIn = true;
			App.checkin_checkout();
		});

		//check if the username was already set for this user
		$(document).delegate("#checkin_continue", "click", function(){
			var username = $.trim($("#username").val());
			var password = $.trim($("#password").val());
			if(username != "") {
				$.username = username;
				$.password = password;
				App.doRequest({action:"login"});
			}else{
				$("#distance").hide();
				$("#distance").html("The username is required");
				$("#distance").fadeIn();
			}
		});
		

        //this should run only once
        $("#menu li a").click(function(){
            $("#menu").hide();
            $(".ui-page-active").animate({marginLeft: 0});
	    $("body").scrollTop(0);
            menuStatus = false;
            var p = $(this).parent();
            if($(p).hasClass('active')){
                $("#menu li").removeClass('active');
            } else {
                $("#menu li").removeClass('active');
                $(p).addClass('active');
            }
        });
        
        setTimeout(function() {
			$("#splash").fadeOut(800);
		}, App.splashScreenDuration);
			
		App.pageInit();
		$(document).bind("pagebeforechange", function() {
			//remove anim-done from previous page's slider
			$(".cherry-slider.anim-done").removeClass("anim-done");
		});
		
		$(document).bind("pageinit", App.pageInit);
		$(document).bind("pageshow", function() {
			$("body").scrollTop(0);
			$("body").scrollTop(0);
			setTimeout(App.windowLoaded, 1000);
		})
    },

    setLoginLogoutLink: function() {
    	var el = $("#login_logout_link");
    	if(typeof localStorage.current_user != "undefined") {
    		$(el).html('<a href="#" data-transition="slide" id="logout" onclick="App.doRequest({action:this.id})" class="contentLink">Logout</a>');
    	}else{
    		$(el).html('<a href="#" data-transition="slide" onclick="App.doCheckin(true);" class="contentLink">Login</a>');
    	}
    },

    doCheckin: function(showLoginForm){
    	console.log(showLoginForm);
    	if(showLoginForm === true) {
    		$(".user_checkin.init").hide();
			$(".user_checkin.credential").fadeIn();
		}

		if(showLoginForm === false) {
			$(".user_checkin.credential").hide();
			$(".user_checkin.init").show();
		}
	},
	
	updatePaymentInfo: function() {
		var val = $.trim($("#payment_rate").val());
		var paymentType = $("#paymentType").val();
		if(isNaN(val)) {
			$("#rate_label").html("Enter numbers only !").css("color", "red");
			$.isValidPayment = false;
			$.invalidReason = "Error: The rate should only be a number.";
			$("#totalDue").html("");
			return;
		}else{
			$("#rate_label").html("Payment rate:").css("color", "black");
			$.isValidPayment = true;
		}
		
		$.totalPaymentDue = val;
		if(paymentType == "hourly") {
			$.totalPaymentDue = val * parseFloat($("#paymentTotalHrs").val());
		}
		
		$("#totalDue").html($.totalPaymentDue);
		$("#paymentAmount").val($.totalPaymentDue);
	},
	
    pageInit: function() {
	
		App.navInit();
			
		setTimeout(function() {
			$('.flexslider:not(.flexslidered)').addClass("flexslidered").flexslider({
				animation: "slide",
				controlNav: false
			});
		}, 1000)
		  
		  
		//custom checkboxes
		$('.on-off:not(.iphoneStyled)').addClass("iphoneStyled").iphoneStyle();
		  
		//initialize photoswipe for portfolio page
		if ($(".photoswipe a:not(.photoSwiped)").length) //dont run if already ran before
		$(".photoswipe a:not(.photoSwiped)").addClass("photoSwiped").click(function(e) {}).photoSwipe({});
		
		$("#menu").hide();
		$(".ui-page-active").css({
			marginLeft: 0
		});
				
		$(".scroll-to-top").click(function() {
			$("body").animate({scrollTop: 0}, 1000);
		});
		
		$("body").scrollTop(0);
		$("body").scrollTop(0);
		setTimeout(App.windowLoaded, 1000);
		
		//maps
		App.refreshMaps();
		App.Forms.bind();
		App.afterPageInit();
    },
	
	getTimesheets: function() {
		$(".top_content").hide();
		$("#timesheetContainer").fadeIn();
		$(".listContainer").trigger('create');
	},
	
	initLocationTracker: function() {
		$(".top_content").hide();
		$("#user_location").fadeIn();
		$(".listContainer").trigger('create');
	},
	
    afterPageInit: function() {
      //tap event effects for links
      $("a:not(.tapInEffected)").addClass("tapInEffected").bind("touchstart mousedown", function() {
         $(this).addClass("hover");
      });
      $("a:not(.tapOutEffected)").addClass("tapOutEffected").bind("touchmove touchend mouseup", function() {
         $(this).removeClass("hover");
      });
      
      
	},
   
	checkin_checkout: function checkin_checkout() {
		if(!confirm("Press OK to confirm !")) return false;
		var isLogedin = App.isLogedin();
		if(!isLogedin) {
			if(localStorage.current_user === undefined) {
				App.doCheckin(true);
			}
		}else{
			$.username = localStorage.current_user;
			$.password = localStorage.current_password;
		}
	},
	
	doRequest: function(params) {

		var dataType 	= (params.dataType !== undefined) ? params.dataType : "jsonp";
		var method 		= (params.method !== undefined) ? params.method : "GET";
		var url 		= (params.url !== undefined) ? params.url : "http://dev.jetcamer.com/babysitter/ws/json.php";
		var action 		= (params.action !== undefined) ? params.action : "checkin";
		var params 		= "getAccountInfo&action="+action+"&username="+$.username+"&password="+$.password;	

		if(action=="checkin" && localStorage.current_user !== undefined) {
			localStorage.isIn = true;
		}

		if(action=="checkout") {
			localStorage.isIn = false;
		}

		App.updateBtnState();

		if(action != "login" && action != "logout") return;
		
		$("#distance").html("Please wait...");

		jQuery.ajax({
			data:params,
			type:method,
			dataType:dataType,
			url: url,
			success: function(o) {
				if(action=="login") {
					if(o.success === true){
						localStorage.current_user = $.username;
						localStorage.current_password = $.password;
						localStorage.role = o.account[0].role;
						App.doCheckin(false);
						App.updateBtnState();
						App.getUsers(false);
					}else{
						$("#distance").html("Oups. User not found !");
					}
				}else{
					
					if(action=="logout") {
						delete localStorage.isIn;
						delete localStorage.current_user;
						delete localStorage.current_password;
						delete localStorage.role;
					}
					App.updateBtnState();
				}

				App.setLoginLogoutLink();
			}
		});
	},
	
	edit_user: function() {
		
		var user_id = $(this).attr("data-userid");
		
		user = App.getUserById(user_id);
		
		var contactForm = $("#editContactTpl").html();
		var el = $("#manage_user .listContainer");
		
		$(el).html(_.template(contactForm, user)).trigger('create');
		$(".top_content").hide();
		$("#manage_user").fadeIn();
	},
	
	makePayment: function() {
		var user_id = $.dyna_userid;
		user = App.getUserById(user_id);
		var hrs = $("#TotalHours").html();
		var period = $("#ts_date_range").val();
		
		if($.trim(period) == "") {
			alert("Please select a period !");
			return;
		}
		
		var el = $("#savePayment.top_content");
		var savePaymentTlp = $("#savePaymentTpl").html();
		console.log(savePaymentTlp);
		el.html(_.template(savePaymentTlp, {user:user, hrs:hrs, period:period})).trigger('create');
		$(".top_content").hide();
		el.fadeIn();
	},
	
	savePayment: function() {
		var params = $( "#paymentForm" ).serialize();
		var isLogedin = App.isLogedin();
		if(isLogedin) {
			var dataType = "json";
			var method = "POST";
			var url = "http://dev.jetcamer.com/babysitter/ws/json.php?savePayment";
			var params = params;	
			
			if($.totalPaymentDue == undefined || $.trim($.totalPaymentDue) == "") {
				alert("Error: No payment amount found !");
				return;
			}
			
			if($.savingPayment === true) return;
			$.savingPayment = true;
			
			$("#payment_loader").html("Please wait...");
			jQuery.ajax({
				data:params,
				type:method,
				dataType:dataType,
				url: url,
				success: function(o) {
					delete $.savingPayment;
					delete $.totalPaymentDue;
					App.getPayment();
				}
			});
		}
	},
	
	getUserById: function(user_id) {
		var user = {"id":0, "username":"", "password":"" ,"fullname":"", "phone":"", "role":""};
		if(parseInt(user_id,10) == 0) return user;
		for (var i=0; i < App.users.length; i++) {
			if(App.users[i].id == user_id) return App.users[i];
		}
		
		return user;
	},
	
	getPayment: function() {
		$(".top_content").hide();
		$("#paymentContainer").fadeIn();
		$("#payment_table tbody").html("");
		$('#payment_users').hide();
		$('#payment').fadeIn(); 
		if($.payment_table === undefined) {
			$.payment_table = $('#payment_table').dynatable({
			  dataset: {
				ajax: true,
				ajaxUrl: 'http://dev.jetcamer.com/babysitter/ws/json.php?getPayment='+ $.pay_userid,
				ajaxOnLoad: true,
				records: []
			  },
			  features: {
				paginate: false,
				recordCount: false,
				sorting: false,
				search: false
			  }
			}).data('dynatable');
		}else{
			$.payment_table.settings.dataset.ajaxUrl = 'http://dev.jetcamer.com/babysitter/ws/json.php?getPayment='+ $.pay_userid;
			$.payment_table.process();
			console.log("payment 2");
		}
	},
	
	save_user: function() {
		var params = $( "#editContactForm" ).serialize();
		if(typeof localStorage.current_user != "undefined") {
			var dataType = "jsonp";
			var method = "GET";
			var url = "http://dev.jetcamer.com/babysitter/ws/json.php?editUser";
			var params = params;	
			
			if($.savingUser === true) return;
			$.savingUser = true;
			$("#user_edit_loader").html("Please wait...");
			jQuery.ajax({
				data:params,
				type:method,
				dataType:dataType,
				url: url,
				success: function(o) {
					$.savingUser = false;
					App.users = o.account;
					App.setUserList();
				}
			});
		}
	},
	
	delete_user: function() {
		if(!confirm("Are you sure you want to delete this user ? !")) return false;
		var user_id = $(this).attr("data-userid");
		var params = "user_id="+user_id+"&username="+localStorage.current_user + "&password=" + localStorage.current_password;
		var isLogedin = App.isLogedin();
		if(isLogedin) {
			var dataType = "jsonp";
			var method = "GET";
			var url = "http://dev.jetcamer.com/babysitter/ws/json.php?deleteUser";
			var params = params;	
			
			$("#user_edit_loader").html("Please wait...");
			jQuery.ajax({
				data:params,
				type:method,
				dataType:dataType,
				url: url,
				success: function(o) {
					App.users = o.account;
					App.setUserList();
				}
			});
		}
	},
	
	setUserList: function(goToUserList) {
		$(".listContainer").html('<ul data-role="listview"></ul>');
		
		var userTpl = $("#userTpl").html();
		var el = $(".listContainer ul");
		$(el).html(_.template(userTpl, {users:App.users})).trigger('create');
		//$(el).listview('refresh');
		
		var userLocationTpl = $("#userLocationTpl").html();
		var el = $("#user_list .listContainer ul");
		$(el).html(_.template(userLocationTpl, {users:App.users})).trigger('create');
		//$(el).listview('refresh');
		
		if(goToUserList === false) return;
		$(".top_content").hide();
		$("#manage_user").fadeIn();
		
		$(".listContainer").trigger('create');
	},
	
	goToHomePage: function() {
		$(".top_content").hide();
		$(".top_content#home").fadeIn();
	},
	
	getUsers: function(goToUserList) {
		var params = "username="+localStorage.current_user + "&password=" + localStorage.current_password;

		//check if the user is logged in. Note: user can be logged in but has checked out.
		if(typeof localStorage.current_user != "undefined") {
			var dataType = "jsonp";
			var method = "GET";
			var url = "http://dev.jetcamer.com/babysitter/ws/json.php?getUsers";
			var params = params;	
			
			$("#user_edit_loader").html("Please wait...");
			jQuery.ajax({
				data:params,
				type:method,
				dataType:dataType,
				url: url,
				success: function(o) {
					App.users = o.account;
					App.setUserList(goToUserList);
				}
			});
		}	
	},
	
	updateBtnState: function updateBtnState() {
		var checkoutBtn = $("#checkout");
		var checkinBtn = $("#checkin");
		var headerMsgEl = $("#distance");
		var isLogedin = App.isLogedin();

		//$("#password").hide();

		if(isLogedin) {
			checkinBtn.attr("style","display:none !important");
			checkoutBtn.attr("style","display:inline-block !important");
			$(headerMsgEl).html("Retrieving your location...");
			App.initialiseMap(); 
			App.LocationTracker();
			$.interval = setInterval(App.LocationTracker, 3000);
		}else{
			checkoutBtn.attr("style","display:none !important");
			checkinBtn.attr("style","display:inline-block !important");
			$("#map_canvas_container").hide();
			try{
				clearInterval($.interval);
				$.interval = null;
			}catch(e){};
			$(headerMsgEl).html("Simple and intuitive");
		}
		
		App.goToHomePage();
	},
	
	isLogedin: function isLogedin() {
		return localStorage.isIn === "true";
	},
	
	initialiseMap: function (el){
		var map_container = (el !== undefined) ? el : $("#map_canvas")[0];
		$('#current').html("Initializing...");
		var myOptions = {
		  zoom: 4,
		  mapTypeControl: true,
		  mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
		  navigationControl: true,
		  navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
		  mapTypeId: google.maps.MapTypeId.ROADMAP      
		}	
		map = new google.maps.Map(map_container, myOptions);
	},
		
	LocationTracker: function (){
		var locations = new Array({ coords: {
				latitude: 	App.initLocation.lat,
				longitude: App.initLocation.lon
			} 
		});
		geoPositionSimulator.init(locations);
		if(geoPosition.init()){
			geoPosition.getCurrentPosition(App.showPosition, function(){$('#current').html("Couldn't get location")},{enableHighAccuracy:true});
		}else{
			$('#current').html("Functionality not available");
		}
	},

	showPosition: function showPosition(p){
		var latitude = parseFloat( p.coords.latitude );
		var longitude = parseFloat( p.coords.longitude );
		var dist = App.calculateDistance(App.initLocation.lat, App.initLocation.lon, latitude, longitude);

		App.saveLocation(latitude, longitude);
		
		if(App.isLogedin()) {
			$('#distance').html("<a style='display:block; color:#199dd4;' href='#' onclick='App.showHideMap()'>Distance: " + parseFloat(dist).toFixed(2) + " " + App.Unit + "<img src='images/map_icon.png' style='margin-left:10px; position:relative; bottom:3px;' /></a>");
		}
		
		$('#current').html("");
		var pos=new google.maps.LatLng( latitude , longitude);
		map.setCenter(pos);
		map.setZoom(14);

		var infowindow = new google.maps.InfoWindow({
			content: "<strong>yes</strong>"
		});

		var marker = new google.maps.Marker({
			position: pos,
			map: map,
			title:"You are here"
		});

		google.maps.event.addListener(marker, 'click', function() {
		  infowindow.open(map,marker);
		});
		
	},

	saveLocation: function checkin_checkout(lat, lon) {
		var isLogedin = App.isLogedin();
		if(isLogedin) {
			var dataType = "jsonp";
			var method = "GET";
			var url = "http://dev.jetcamer.com/babysitter/ws/json.php";
			var params = "saveLocation&username="+localStorage.current_user+"&lat="+lat+"&lon="+lon;	
			
			$("#distance").html("Please wait...");
			jQuery.ajax({
				data:params,
				type:method,
				dataType:dataType,
				url: url,
				success: function(o) {
					
				}
			});
			
		}
	},

	viewLocation: function(username) {
		$("#user_map_canvas").html("").hide();
		
		var isLogedin = App.isLogedin();
		if(isLogedin) {
			var dataType = "jsonp";
			var method = "GET";
			var url = "http://dev.jetcamer.com/babysitter/ws/json.php";
			var params = "getLocation&username="+username;	
			
			$("#user_map_header").html("Please wait...");
			jQuery.ajax({
				data:params,
				type:method,
				dataType:dataType,
				url: url,
				success: function(o) {
					
					if(o.success) {
						if(o.lat !== undefined){
							var locations = new Array({ coords: {
									latitude: 	o.lat,
									longitude: o.lon
								} 
							});

							$("#user_map_canvas").show();
							App.initialiseMap($("#user_map_canvas")[0]);
							App.showPosition(locations[0]);
							$("#user_map_header").html("<span class='username_map'>" + username + " lastest location</span>");
						}
						
					}else{
						$("#user_map_header").html("<span class='username_map'>" + username + "</span> haven't used the app yet !");
					}
					
				}
			});	
		}

	},
		
	// Reused code - copyright Moveable Type Scripts - retrieved May 4, 2010.
	// http://www.movable-type.co.uk/scripts/latlong.html
	// Under Creative Commons License http://creativecommons.org/licenses/by/3.0/
	calculateDistance: function calculateDistance(lat1, lon1, lat2, lon2) {
		var R = 6371; // km
		
		var lat1 = parseFloat(lat1);
		var lon1 = parseFloat(lon1);
		var lat2 = parseFloat(lat2);
		var lon2 = parseFloat(lon2);
		
		var dLat = (lat2-lat1).toRad();
		var dLon = (lon2-lon1).toRad();
		
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		
		var d = R * c;
		return d;
	},
	
	showHideMap: function() {
		var el = $("#map_canvas_container");
		if(el.is(":visible")) {
			el.hide();
		}else{
			el.show();
			App.initialiseMap();
		}
	},

    navInit: function() {
        
        //$.event.special.swipe.horizontalDistanceThreshold = 100;
        
	$(".slider-component, .prevent-swipe-menu").bind("swiperight", function(e) {
		e.stopPropagation();
	});
	
        $('.pages').bind("swipeleft", function(){
                $(".ui-page-active").css({
                    marginLeft: "0px",
                }, 300,
                function(){
                    menuStatus = false;
                    $("#menu").hide();
                });
        });
        $('.pages').bind("swiperight", function(){
				if ($(".pages").width() < 1010)
					return;
                $("#menu").show();

                $(".ui-page-active").css({
                    marginLeft: "165px",
                }, 300, function(){
                    menuStatus = true
                });
				$("body").animate({scrollLeft: 0, scrollTop: 0});
        });
        $("a.back-button").click(function(e) {
            e.preventDefault();
            history.back();
        });
        $("a.showMenu").click(function(){
            if(menuStatus != true){
                $("#menu").show();
                $(".ui-page-active").css({
                    marginLeft: "165px",
                });
		menuStatus = true;
                return false;
            } else {
                $(".ui-page-active").css({
                    marginLeft: "0px",
                });
		menuStatus = false;
                return false;
            }
        });
        
        
        
    },
    windowLoaded: function() {
        //cherry slider
        if ($(".cherry-slider:not(.anim-done)").length) {
            $.each($(".cherry-slider"), function(i, elem) {
                App.cherrySliderInit(elem)
            });
        }
    },
    refreshMaps: function(){
	if (!$(".map").length)
	   return;
	$('.map').each(function(){
	     var me = $(this);
	     var locationTitle = $(this).attr('data-location');
	     var myId = $(me).attr('id');
	     var geocoder = new google.maps.Geocoder();
	     geocoder.geocode({
		  address: locationTitle
	      }, function(locResult) {
		  var latVal = locResult[0].geometry.location.lat();
		  var longVal = locResult[0].geometry.location.lng();
		  App.initializeMap(myId, locationTitle, latVal, longVal);
	      });
	});
     },
     initializeMap: function(locationVal, titleVal, latVal, longVal) {
	var latlng = new google.maps.LatLng(latVal, longVal);
	var settings = {
		zoom: 13,
		center: latlng,
		mapTypeControl: false,
		mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
		navigationControl: false,
		navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
		streetViewControl: false,
		zoomControl: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP 
	};
	var map = new google.maps.Map($('#current').html("#"+locationVal), settings);
	
	
	var nibrasPos= new google.maps.LatLng(latVal, longVal);
	var nibrasMarker = new google.maps.Marker({
		  position: nibrasPos,
		  map: map,
		  title:titleVal
	});
     },
    cherrySliderInit: function(elem) {
        var sliderHelper = {
            myParseInt: function(val) {
                if (val == undefined)
                    return undefined;
                if (val.indexOf("%") >= 0)
                    return val;
                else
                    return parseInt(val)
            },
            animate: function(item) {
		if (!$(elem).is(":visible")) {
			return;
		}
                //decide anim
                var anim = item.attr("anim");
                var direction = item.attr("anim-direction");
                var left = sliderHelper.myParseInt(item.attr("anim-position-left"));
                var right = sliderHelper.myParseInt(item.attr("anim-position-right"));
                var top = sliderHelper.myParseInt(item.attr("anim-position-top"));
                var animSpeed = sliderHelper.myParseInt(item.attr("anim-speed"));
		var times = sliderHelper.myParseInt(item.attr("anim-times"));
                var action = item.attr("anim-action");
                if (action == "restart") {
                    setTimeout(function() {
                        sliderHelper.animate(item.parent().find(".anim-item:first"));
                    }, animSpeed);
                } else if (action == "break") {
                    if (anim == "fade") {
                        item.prevAll(".anim-item").fadeOut(animSpeed);
                    } else {
                        item.prevAll(".anim-item").effect(anim, {mode: "hide", direction: direction}, animSpeed);
                    }
                    setTimeout(function() {
                        if (item.next().hasClass("anim-item"))
                            sliderHelper.animate(item.next())
                    }, animSpeed);

                } else if (anim == "slide") {
                    if (direction == "right" && left)
                        item.css({left: $(item).parents(".cherry-slider").width()});
                    if (direction == "left" && right)
                        item.css({right: $(item).parents(".cherry-slider").width()});
                    if (direction == "down")
                        item.css({top: $(item).parents(".cherry-slider").height()});
                    item.css({opacity: 0}).show();
                    item.animate({opacity: 1, right: right, left: left, top: top}, parseInt(animSpeed), function() {
                        if (item.next().hasClass("anim-item"))
                            sliderHelper.animate(item.next())
                    });
                } else if (anim == "fade") {
                    
                    item.css({opacity: 0, right: right, left: left, top: top});
                    item.show();
                    item.animate({opacity: 1}, parseInt(animSpeed), function() {
                        if (item.next().hasClass("anim-item"))
                            sliderHelper.animate(item.next())
                    });
                } else if (anim == "drop") {
                    if (right != undefined)
                        left = $(item).parents(".cherry-slider").width() - right - item.width();
                    item.css({opacity: 1, left: left, top: top});
                    //item.hide();
                    item.effect("drop", {mode: "show", distance: 8, direction: direction}, animSpeed, function() {
                        if (item.next().hasClass("anim-item"))
                            sliderHelper.animate(item.next())
                    });
                } else if (anim == "bounce") {
                    if (right != undefined)
                        left = $(item).parents(".cherry-slider").width() - right - item.width();
                    item.css({opacity: 1, left: left, top: top});
                    item.hide();
                    item.effect("bounce", {times: (times == undefined ? 1 : times), distance: 10, mode: "show", direction: direction}, animSpeed, function() {
                        if (item.next().hasClass("anim-item"))
                            sliderHelper.animate(item.next())
                    });
                    
                } else if (anim == "puff") {
                    if (right != undefined)
                        left = $(item).parents(".cherry-slider").width() - right - item.width();
                    item.css({opacity: 1, left: left, top: top});
                    item.hide();
                    item.effect("puff", {mode: "show", direction: direction}, animSpeed, function() {
                        if (item.next().hasClass("anim-item"))
                            sliderHelper.animate(item.next())
                    });
                } else if (anim == "blind") {
                    if (right != undefined)
                        left = $(item).parents(".cherry-slider").width() - right - item.width();
                    item.css({opacity: 1, left: left, top: top});
                    item.hide();
                    item.effect("blind", {mode: "show", direction: direction}, animSpeed, function() {
                        if (item.next().hasClass("anim-item"))
                            sliderHelper.animate(item.next())
                    });
                }
            }
        }
	if ($(elem).hasClass("anim-done")) {
            //restart anim
	    $(".anim-item").effect("fade", {mode: "hide"}, 100, function() {
		sliderHelper.animate($(".anim-item:first", $(elem)));
	    });
	    return;
        }
        else
            $(elem).addClass("anim-done");
        
        $(".anim-item", elem).css({opacity: 0}).show();
        var currentItem = $(".anim-item:first", elem);
        sliderHelper.animate(currentItem);
    },
    Util: {
	mobile: {
         detect:function(){
            var uagent = navigator.userAgent.toLowerCase(); 
            var list = this.mobiles;
            var ismobile = false;
            for(var d=0;d<list.length;d+=1){
                    if(uagent.indexOf(list[d])!=-1){
                            ismobile = list[d];
                    }
            }
            return ismobile;
         },
         mobiles:[
            "midp","240x320","blackberry","netfront","nokia","panasonic",
            "portalmmm","sharp","sie-","sonyericsson","symbian",
            "windows ce","benq","mda","mot-","opera mini",
            "philips","pocket pc","sagem","samsung","sda",
            "sgh-","vodafone","xda","palm","iphone",
            "ipod","android"
         ]
       }
    },
    Forms: {
      bind: function() {
         // Add required class to inputs
         $(':input[required]').addClass('required');
         
         // Block submit if there are invalid classes found
         $('form.ajax-form:not(.html5enhanced)').addClass("html5enhanced").submit(function() {
               var formEl = this;
                 $('input,textarea').each(function() {
                         App.Forms.validate(this);
                 });
                 
                 if(($(this).find(".invalid").length) == 0){
                         // Delete all placeholder text
                         $('input,textarea').each(function() {
                                 if($(this).val() == $(this).attr('placeholder')) $(this).val('');
                         });
                         

						//submit without ajax
						if ($(formEl).hasClass("no-ajax")) {
							return true;
						}
						
                         //if it reached here, submit form via ajax
                         $.ajax({
                           url: $(formEl).attr("action"),
                           type: $(formEl).attr("method"),
                           data: $(formEl).serialize(),
                           success: function(r) {
                              if (r) {
                                 $(".success-message").slideDown().removeClass("hidden");
                              }
                           }
                         })
                         return false;
                 }else{
                         return false;
                 }
         });

      },
      is_email: function(value){
	return (/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/).test(value);
      },
      is_url: function(value){
              return (/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i).test(value);
      },
      is_number: function(value){
              return (typeof(value) === 'number' || typeof(value) === 'string') && value !== '' && !isNaN(value);
      },
      validate: function(element) {
         var $$ = $(element);
         var validator = element.getAttribute('type'); // Using pure javascript because jQuery always returns text in none HTML5 browsers
         var valid = true;
         var apply_class_to = $$;
         
         var required = element.getAttribute('required') == null ? false : true;
         switch(validator){
                 case 'email': valid = App.Forms.is_email($$.val()); break;
                 case 'url': valid = App.Forms.is_url($$.val()); break;
                 case 'number': valid = App.Forms.is_number($$.val()); break;
         }
         
         // Extra required validation
         if(valid && required && $$.val().replace($$.attr('placeholder'), '') == ''){
                 valid = false;
         }
         
         // Set input to valid of invalid
         if(valid || (!required && $$.val() == '')){
                 apply_class_to.removeClass('invalid');
                 apply_class_to.addClass('valid');
                 return true;
         }else{
                 apply_class_to.removeClass('valid');
                 apply_class_to.addClass('invalid');
                 return false;
         }
      }

   }

}


$(App.init);
