var FoodArena = FoodArena || {}

FoodArena.networking = ( function($) {"use strict";

    var restaurantUrl  = "http://www.foodarena.ch/serve_search_xml.php";
    var menuUrl        = "http://www.foodarena.ch/serve_menu_xml.php";
    var getUserUrl     = "http://www.foodarena.ch/serve_user_xml.php";
    var newUserUrl     = "http://www.foodarena.ch/serve_reg_usr.php";
    var sendOrderUrl   = /*"http://fpmsoft.com/tmp/in/in.php";//"*/"http://www.foodarena.ch/send_order_external.php";
    
    
    var getDeliveryUrl = "http://www.foodarena.ch/serve_future_times_xml.php";
	var checkVoucherUrl = "http://www.foodarena.ch/serve_check_voucher_xml.php";
   
    var getRestaurantsList = function(zip) {
        var url = restaurantUrl + "?criteria=" + zip;
        var restaurants = new Array();
       $.ajax({
            type : "GET",
            timeout : 50000,
            url : url,
            dataType : "xml",
            async : true,
            error : function(x, e) {
                console.log("getRestaurantsList err:" + x.statusText + " error:" + e + " ");
            }, 
            beforeSend : function() {
             },
            complete : function() {
            },
            success : function(xml, textStatus, jqXHR) {
                var restaurant;
                $(xml).find('restaurant').each(function(i) {
                    restaurant = new Restaurant($(this));
                     restaurants.push(restaurant);
                 });
				 loadReataurants();
            }
        });
        return restaurants;
    };
    
       var getDeliveryTimeList = function(restaurantId, delivCheck) {
        var url = getDeliveryUrl + "?rest_id=" + restaurantId + "&deliv_check=" + delivCheck;
        var times = new Array();
		var unixTimes = new Array();
       $.ajax({
            type : "GET",
            timeout : 50000,
            url : url,
            dataType : "xml",
            async : true,
            error : function(x, e) {
                console.log("getDeliveryTimeList err:" + x.statusText + " error:" + e + " ");
            }, 
            beforeSend : function() {
             },
            complete : function() {
            },
            success : function(xml, textStatus, jqXHR) {
                $(xml).find('future_times').each(function(i) {
                      $(this).find('time').each(function(j) {        
                           // console.log(timeConverter($(this).text()));
                           // restaurant = new Restaurant($(this));
                           times.push(timeConverter($(this).text()));
						   unixTimes.push($(this).text());
                      });
                 });
				Storage.curDeliveryTimes = unixTimes;
				Storage.curDeliveryTime = times;
				if(Storage.curRestaurantMenu && Storage.curRestaurantMenu.menuGroups){
					order();
				}
            }
        });
        return times;
    };
    

    var getMenuList = function(restaurantId) {
        var url = menuUrl + "?id=" + restaurantId;
        var menu = null;
       $.ajax({
            type : "GET",
            timeout : 50000,
            url : url,
            dataType : "xml",
            async : true,
            error : function(x, e) {
                console.log("getMenuList err:" + x.statusText + " error:" + e + " ");
            }, 
            beforeSend : function() {
             },
            complete : function() {
            },
            success : function(xml, textStatus, jqXHR) {
                menu = new Menu(xml);
				Storage.curRestaurantMenu = menu;
				if(Storage.curDeliveryTimes && Storage.curDeliveryTimes.length > 0){
					order();
				}
             }
        });
        return menu;
    };
    
    var getUserInfo = function(email, pass) {
        var url = getUserUrl + "?email=" + email + "&passwd=" + pass;
        var user = null;
       $.ajax({
            type : "GET",
            timeout : 50000,
            url : url,
            dataType : "xml",
            async : false,
            error : function(x, e) {
                console.log("getUserInfo err:" + x.statusText + " error:" + e + " ");
            }, 
            beforeSend : function() {
             },
            complete : function() {
            },
            success : function(xml, textStatus, jqXHR) {
                user = new UserResult($(xml).find('user_result').first());
            }
        });
        return user;
    };
    

     var registerNewUser = function(email, name, vorname, password, passwordConf, strasse, nr, plz, ort) {
        var url = newUserUrl;
        var result = null;
       $.ajax({
            type : "POST",
            timeout : 50000,
            url : url,
            data: {
                email : email,
                name : name,
                vorname : vorname,
                password : password,
                password_conf : passwordConf,
                strasse : strasse,
                nr : nr,
                plz : plz,
                ort : ort
            },
            dataType : "xml",
            async : false,
            error : function(x, e) {
                console.log("registerNewUser err:" + x.statusText + " error:" + e + " ");
            }, 
            beforeSend : function() {
             },
            complete : function() {
            },
            success : function(xml, textStatus, jqXHR) {
                result = new UserRegistrationResult($(xml).find('result').first());
            }
        });
        return result;
    };
    
    var sendOrder = function(order) {
        var url = sendOrderUrl;
        var result = null;
        var paymentType = order.paymentType == 0 ? "cash" :"card"; 
        try{
       $.ajax({
            type : "POST",
            timeout : 50000,
            url : url,
            data: {
                'order' : order.items,
                'company':order.company,
                'name':order.name,
                'vorname':order.vorname,
                'strasse':order.strasse,
                'nr':order.nr,
                'floor_nr':order.floor_nr,
                'plz':order.plz,
                'ort':order.ort,
                'email':order.email,
                'DOB_day':order.DOB_day,
                'DOB_month':order.DOB_month,
                'DOB_year':order.DOB_year,
                'phone':order.phone,
                'special_instructions':order.special_instructions,
                'user_id':order.user_id,
                'deliv_check':order.deliv_check,
                'future_time':order.future_time,
                'deliv_cost':order.deliv_cost,
                'id':order.id,
                'order_from':order.order_from,
                'payment_type':paymentType,
                'lang':Storage.langStr
            },
            //dataType : "xml",
            dataType: "text",
            async : true,
            error : function(x, e) {
                console.log("send order err:" + x.statusText + " error:" + e + " ");
                alert("send order err:" + x.statusText + " error:" + e + " ");
            	$.mobile.loading('hide');
            }, 
            beforeSend : function() {
            	$.mobile.loading('show');
             },
            complete : function() {
            	$.mobile.loading('hide');
            },
            success : function(xml, textStatus, jqXHR) {
              // alert(xml);
                //result = new UserRegistrationResult($(xml).find('result').first());
                //console.log("send order success" + simpleObjInspect(jqXHR));
                console.log("send order success" + $(xml).find('order_result').first().children('error').text());
                //alert($(xml).find('order_result'));
                processOrderResult(xml);
                $.mobile.loading('hide');
            }
        });}catch(err){
        	alert(err.message);
        }
        return result;
    };
	
	var checkVoucher = function(voucher) {
        var url = checkVoucherUrl + "?voucher_code=" + voucher.voucherCode + "&restaurant_id=" + voucher.restaurantId + "&order_value=" + voucher.orderValue;
        var restaurants = new Array();
       $.ajax({
            type : "GET",
            timeout : 50000,
            url : url,
            dataType : "xml",
            async : true,
            error : function(x, e) {
                console.log("checkVoucher err:" + x.statusText + " error:" + e + " ");
            }, 
            beforeSend : function() {
             },
            complete : function() {
            },
            success : function(xml, textStatus, jqXHR) {
            	$.mobile.loading( 'hide' );
				processVoucherResult($(xml).find('voucher_check_result'));
            }
        });
        return null;
    };
    


    var init = function() {
    };
    
    var pub = {
        init : init,
        getRestaurantsList : getRestaurantsList,
        getMenuList : getMenuList,
        getUserInfo : getUserInfo,
        registerNewUser : registerNewUser,
        sendOrder : sendOrder,
		checkVoucher : checkVoucher,
        getDeliveryTimeList : getDeliveryTimeList
		
    };

    return pub;

}(jQuery));
