var SERVICES = {
    "setUserInfo":function() {
	var fname = $('#fname').val();
	var lname = $('#lname').val();
	var phone = $('#phone').val();
	if (!fname || !lname || !phone) {
		alert('All fields are required.');
		return false;
	}
	$.ajax({
	 	type: 'POST',
		url: '/services/',
		data: {action:'setUserInfo',fname:fname,lname:lname,phone:phone},
		dataType: 'html',
		success: function(success) {
			if (success==1) {
				alert('Your information has been saved and you are now associated with this store.');
				location.reload(true);				
			} else {
				alert(success);
			}
		},async:false	
	});
     },
    "setStoreId":function(store_id){
    if (!store_id) store_id = '';
       $.ajax({
		type: 'POST',
		url: '/services/setStoreID/',
		data: {store_id:store_id},
		dataType: 'json',
		success: function(obj) {
			 if (obj.result == "success") {
			   //alert(obj.message);
			   //show the name check div
			   $('#store-association').jqmHide();
			   $('#name-check-div').jqm({modal:true}).jqmShow();
			   $('#fname').val(obj.fname);
			   $('#lname').val(obj.lname);
			   $('#phone').val(obj.phone);
			 } else {
			   //alert(obj.message);
			   alert('Store ID assignment failed.');
			   location.reload(true);
			 } 
		}
       }); //end ajax call
    },    
        "login":function(redirect){
            var usrnm = $('#username').val();
            var psswd = $('#password').val();

            if(usrnm != '' && psswd != '') {

            	$.ajax({
            		type: 'POST',
            		url: '/services/login/',
            		data: {username: usrnm, password: psswd},
            		dataType: 'json',
            		success: function(obj) {
        			if(obj.result == "success") {
            				$('#login').jqmHide();
					/**
					/* gets the current user information from the cookie
					/* uses php imitation functions from php.js
					/* unserialize and base_decode
					/* and jquery.cookie.js for cookie access
					/* @param object $userobj - the current user's information
					**/
					var theinfo = $.cookie('LOGIN_INFO');
					if(theinfo==null||theinfo==''){
						theinfo = obj.info;
					}
					var userobj = unserialize(base64_decode(theinfo));
					//userobj.storeId is the store id of the user.
					//RETAILERID is the current store's retailer id
					if (userobj.storeId != RETAILERID && $.inArray(parseInt(userobj.storeId),franchiseStoreIDs)==-1) {
					   $('#store-association').jqm({modal:true}).jqmShow();
					} else if (redirect == "submit cart") {
					   isloggedin = 1;
					   $('#checkout_submit').click();
					} else if (redirect) {
					   window.location = redirect;
					} else {
					   location.reload(true);
					}
            			} else {
            				alert("An error has occured: "+obj.message);
            			}
            		},
            		error: function (XMLHttpRequest, textStatus, errorThrown) {
            				alert("Unable to login at this time. " + textStatus + '->' + errorThrown);
            		}
            	});  //end ajax call
            }
            
        }, // end login
        
        "pullList":{
	    "addOneToQty":function(itemID){
		$.ajax({
			type: 'POST',
			url: '/services/pulllist/add_qty/',
			data: {'itemID':itemID},
			dataType: 'json',
			success: function (obj) {
				if (obj.success == true) {
					return true;
				} else {
					alert(obj.error);
				}
			},async: false
		});
		return true;
	    },
	    "subtractOneFromQty":function(itemID) {
		$.ajax({
			type: 'POST',
			url: '/services/pulllist/subtract_qty/',
			data: {'itemID':itemID},
			dataType: 'json',
			success: function (obj) {
				if (obj.success) {
					return true;
				} else {
					alert(obj.error);
				}
			},async: false
		});
		return true;
	    },
            "addItem":function(itemID){
                //console.log(itemID);
                if(itemID != ''){
                    $.ajax({
                		type: 'POST',
                		url: '/services/pulllist/add/',
                		data: {"itemID": itemID},
                		dataType: 'json',
                		success: function(obj) {
                		    //console.log(obj);
                		    if(obj['result'] == 'success'){
                		        $btn = $('#item-btn-'+itemID);
					$pull_btn = $('#pull_buttons_'+itemID);
                		        //toggle styles
					$('#pull_number_'+itemID).html(1);
					$btn.hide();
					$pull_btn.show();
                		        //$btn.removeClass('addItem');
                		        //$btn.addClass('removeItem');
                		        //redelegate events
                		        //$btn.unbind('click');  //<unbind old click event
                		        //$btn.bind('click',ACTIONS.PullList.removeItemClickToggleBtn);
                		    } else if (obj['result'] == 'error') {
				       alert(obj['message']);
				    }
                		    return true;
                			
                		},
                		error: function (XMLHttpRequest, textStatus, errorThrown) {
                				alert("Unable to Post your comments at this time. " + textStatus + '->' + errorThrown + XMLHttpRequest.responseText);
                		}
                	});  //end ajax call
                }
            },
            "removeItem":function(itemID, actions){
                //console.log(itemID);
                if(itemID != ''){
                    $.ajax({
                		type: 'POST',
                		url: '/services/pulllist/remove/',
                		data: {"itemID": itemID},
                		dataType: 'json',
                		success: function(obj){
                		    if (obj['result'] == 'error') {
				       alert(obj['message']);
				    } else {
				       actions['success'](obj,itemID);
				    }
                		},
                		error: function (XMLHttpRequest, textStatus, errorThrown) {
                				alert("Unable to Post your comments at this time. " + textStatus + '->' + errorThrown + XMLHttpRequest.responseText);
                		}
                	});  //end ajax call
                }
            }
        }, // end pullist closure
        "browseBox":{
            "getBrowseBox":function(year, month){

                $.ajax({
                    type: 'POST',
            		url: '/services/browsebox/date/'+year+'/'+month+'/',
            		data: '',
            		dataType: 'json',
            		success: function(obj) {
            			var $ulControl = $("#browse-box-weeks-control");
            			var totalRecords = obj.length;
				
            			var liHTML = ''
            			for(ctr=0; ctr < totalRecords; ctr++){
            			    liHTML += '<li><a href="'+BROWSEBOX.url+obj[ctr]['url']+'">'+obj[ctr]['label']+'</a></li>';
            			}
            			$liHTML = jQuery(liHTML);
            			$ulControl.empty().append($liHTML);
            		},
            		error: function (XMLHttpRequest, textStatus, errorThrown) {
            				//console.log('browse-box failed to load');
            		}
                });
            }
        }, //end browsebox
        'subscription':{
            'addSubscription':function(params){
                if(params['itemID'] != '' && params['seriesID'] != ''){
                    $.ajax({
                		type: 'POST',
                		url: '/services/subscription/subscribe/',
                		data: {"itemID": params['itemID'], 'seriesID': params['seriesID']},
                		dataType: 'json',
                		success: function(obj) {
                		    if(obj['result'] == 'success'){
                		        //swap out image
                		        $subscribeBtn = $('#subscribe-'+params['itemID']);
                		        $subscribeBtn.removeClass('addSubscription');
                		        //when switching to edit subscription need to had standard link in
                		        $subscribeBtn.addClass('editSubscription');
                		        $subscribeBtn.append('<a href="/subscriptions/?seriesid='+params['seriesID']+'">edit subscription</a>');
                		        $subscribeBtn.unbind('click');
                		    }
                		},
                		error: function (XMLHttpRequest, textStatus, errorThrown) {
                				alert("Unable to Post your comments at this time. " + textStatus + '->' + errorThrown);
                		}
                	});  //end ajax call
                }
            },
            'removeSubscription':function(params){
                if(params['removeFromPullList'] != '' && params['seriesID'] != ''){
                    $.ajax({
                		type: 'POST',
                		url: '/services/subscription/unsubscribe/',
                		data: {'seriesID': params['seriesID'], 'removeFromPullList':params['removeFromPullList']},
                		dataType: 'json',
                		success: function(obj) {
                		    if(obj['result'] == 'success'){
                		        $('div.subscriptionFrame > div').removeClass('alt'); //< remove alt strip on all items
                		        //if success then remove the html block
                		        $('div.subscriptionFrame > div').each(function(){
                		           $this = jQuery(this);
                		           var containerID = $this.attr('seriesid');
                		           if(containerID == params['seriesID']){
                		               $this.remove();
                		           }
                		        });
                		        //do loop again to redraw stripes
                		        $('div.subscriptionFrame > div').each(function(index){
                		           $this = jQuery(this);
                                   if(index % 2){
                                       $this.addClass('alt');
                                   }
                		        });
                		    }
                		},
                		error: function (XMLHttpRequest, textStatus, errorThrown) {
                				alert("Unable to Post your comments at this time. " + textStatus + '->' + errorThrown);
                		}
                	});  //end ajax call
                }
            },
            'updateSubscription':function(params){
                $.ajax({
            		type: 'POST',
            		url: '/services/subscription/update/seriesid/'+params['seriesID']+'/variant/'+params['variant']+'/reprint/'+params['reprint']+'/',
            		data: params['formats'],
            		dataType: 'json',
            		success: function(obj) {
            		    if(obj['result'] == 'success'){
            		        $('div.subscriptionFrame > div').each(function(index){
            		            $this = jQuery(this);
                		        var containerID = $this.attr('seriesid');
                		        if(containerID == params['seriesID']){
                                    //this is the element we want to be in
                                    var htmlString =  'Subscription Updated - '+obj['itemsAdded']+' New Items were added to your pullList and '+obj['itemsRemoved']+' items were deleted';
                                    $subUpdatePanel = $this.find('.subscription-update');
                                    $subUpdatePanel.html(htmlString);
                                    $subUpdatePanel.addClass('show');
                		        }
            		        });
            		    }
            		},
            		error: function (XMLHttpRequest, textStatus, errorThrown) {
            				alert("Unable to Post your comments at this time. " + textStatus + '->' + errorThrown);
            		}
            	});  //end ajax call
            }
        }
    
    }

