﻿
    var _userId, _currentGameId, gamedetail, map, locations, centerlocation;
    var myfood, foodgroup, wheatgroup, vegetablegroup, fruitgroup, diarygroup, meatgroup, extrasgroup;
    var eat, learn, play;

    function newGameAdded(gameid, jsonArray) {
    	setSingleMarker(map, jsonArray);

    	var json = new Object();
    	json.GameId = parseInt(gameid, 10);
    	json.UserId = parseInt(_userId);
    	sendAJAX('GetGameDetailByGameId', json, null);
    }

    function guestclick() {
        $.BadBox({ width: 500, height: 100, iframe: "/badbox/LoginRequired.aspx" });
        return false;
    }
    
    function dispatchFilterClick(e) {
        var target = $(e.target);
        if (target.is("#allfilter")) {
            foodgroup.children('div').removeClass('invisible');
        }
        else if (target.is('#wheatfilter')) {
            wheatgroup.removeClass('invisible').siblings('div').addClass('invisible');
        }
        else if (target.is('#vegetablefilter')) {
            vegetablegroup.removeClass('invisible').siblings('div').addClass('invisible');
        }
        else if (target.is('#fruitsfilter')) {
            fruitgroup.removeClass('invisible').siblings('div').addClass('invisible');
        }
        else if (target.is('#diaryfilter')) {
            diarygroup.removeClass('invisible').siblings('div').addClass('invisible');
        }
        else if (target.is('#meatfilter')) {
            meatgroup.removeClass('invisible').siblings('div').addClass('invisible');
        }
        else if (target.is('#extrasfilter')) {
            extrasgroup.removeClass('invisible').siblings('div').addClass('invisible');
        }
    }

    function dispatchRemoveFood(e) {
        $(e.target).parent('a').remove();
    }
    //dispatchCreateGameClick
    //click on create a game
    //
    //@param e : object : event object
    function dispatchCreateGameClick(e) {
        $.BadBox({ width: 800, height: 600, iframe: "/badbox/AddGame.aspx" });
        return false;
    }

    function HomeControl(controlDiv, map) {

    	// Set CSS styles for the DIV containing the control
    	// Setting padding to 5 px will offset the control
    	// from the edge of the map
    	controlDiv.style.padding = '5px';

    	// Set CSS for the control border
    	var controlUI = document.createElement('DIV');
    	controlUI.style.backgroundColor = 'white';
    	controlUI.style.borderStyle = 'solid';
    	controlUI.style.borderWidth = '2px';
    	controlUI.style.cursor = 'pointer';
    	controlUI.style.textAlign = 'center';
    	controlUI.title = 'Click to set the map to Home';
    	controlDiv.appendChild(controlUI);

    	// Set CSS for the control interior
    	var controlText = document.createElement('DIV');
    	controlText.style.fontFamily = 'Arial,sans-serif';
    	controlText.style.fontSize = '12px';
    	controlText.style.paddingLeft = '4px';
    	controlText.style.paddingRight = '4px';
    	controlText.innerHTML = 'Change Location';
    	controlUI.appendChild(controlText);

    	// Setup the click event listeners: simply set the map to
    	// Chicago
    	google.maps.event.addDomListener(controlUI, 'click', function() {
    		$('#locationmodal').toggle();
    	});
    }


    //initialize
    //initialize the map when page starts
    //
    function initialize() {
        centerlocation = new google.maps.LatLng(jsLatitude, jsLongitude);
        var myOptions = {
        zoom: 10,
			mapTypeControl: true,
			mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
            center: centerlocation,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var homeControlDiv = document.createElement('DIV');
        var homeControl = new HomeControl(homeControlDiv, map);

        homeControlDiv.index = 1;
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);


        locations = jsLocationName;
        setMarkers(map, locations);
    }

    //Update the map based on coordinate given
    function UpdateCurrentMap() {
        map.clearOverlays();

        centerlocation = new google.maps.LatLng(jsLatitude, jsLongitude);
        map.setCenter(centerlocation);
        locations = jsLocationName;

        setMarkers(map, locations);
    }

    //Test functionality to show the arrays
    function ShowArrayContents() {
        var allElements = '';
        for (var i = 0; i < jsLocationName.length; i++)
            allElements += jsLocationName[i] + "\n";
        alert(allElements);
        return false;
    }

    //Set the marker on the map
    function setMarkers(map, location) {
        // Add markers to the map
        var shape = {
            coord: [1, 1, 1, 20, 18, 20, 18, 1],
            type: 'poly'
        };
        for (var i = 0; i < locations.length; i++) {
            var location = locations[i];
            var myLatLng = new google.maps.LatLng(location[1], location[2]);
            var imageurl = getMapImageByGameTypeId(location[3], 32);

            var image = new google.maps.MarkerImage(imageurl,
            // This marker is 20 pixels wide by 32 pixels tall.
			  new google.maps.Size(32, 32),
            // The origin for this image is 0,0.
			  new google.maps.Point(0, 0),
            // The anchor for this image is the base of the flagpole at 0,32.
			  new google.maps.Point(0, 32));

            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                //shadow: null,
                icon: image,
                //shape: shape,
                title: location[0]
                //zIndex: beach[3]
            });

            var GameId = location[4];
            showGameDetail(marker, GameId);
        }
       }

       //Set the marker on the map
       function setSingleMarker(map, singlelocation) {
       	// Add markers to the map
       	var shape = {
       		coord: [1, 1, 1, 20, 18, 20, 18, 1],
       		type: 'poly'
       	};
       	
       		//var location = singlelocation;
       		var myLatLng = new google.maps.LatLng(singlelocation[1], singlelocation[2]);
       		var imageurl = getMapImageByGameTypeId(singlelocation[3], 32);

       		var image = new google.maps.MarkerImage(imageurl,
       		// This marker is 20 pixels wide by 32 pixels tall.
			  new google.maps.Size(32, 32),
       		// The origin for this image is 0,0.
			  new google.maps.Point(0, 0),
       		// The anchor for this image is the base of the flagpole at 0,32.
			  new google.maps.Point(0, 32));

       		var marker = new google.maps.Marker({
       			position: myLatLng,
       			map: map,
       			//shadow: null,
       			icon: image,
       			//shape: shape,
       			title: singlelocation[0]
       			//zIndex: beach[3]
       		});

       		var GameId = singlelocation[4];
       		showGameDetail(marker, GameId);
       	
       }


    // The five markers show a secret message when clicked
    // but that message is not within the marker's instance data
    function showGameDetail(marker, GameId) {
        google.maps.event.addListener(marker, 'click', function() {
            var json = new Object();
            json.GameId = parseInt(GameId, 10);
            json.UserId = parseInt(_userId);
            sendAJAX('GetGameDetailByGameId', json, marker);
            //alert(json.GameId);
            //$.BadBox({ width: 800, height: 600, iframe: "/badbox/GameDetail.aspx?GameId=" + GameId });

            //WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$body$lnkGameDetail", "", false, "", "#sportsection", false, true));
        });
    }

    function handleGetGameDetail(response, target) {
        var picture = getMapImageByGameTypeId(response.GameTypeId, 128);
        var button;
        if (response.InGame) {
        	button = '<a href="javascript:;" id="btnleave" name="btnleave">Can\'t make it</a>';
        }
        else {
        	button = '<a href="javascript:;" id="btnjoin" name="btnjoin">Join Game</a>';
        }

        _currentGameId = parseInt(response.GameId);

        var html = $('<div>' +
						'<img src="' + picture.toString() + '" alt="' + response.Description + '" /> <br />' +
						'<h3><b>' + response.LocationName + '</b> (' + response.Description + ')</h3>' +
						'<address>' + response.Address + '<br />' + response.City + ', ' + response.State + '</address>' +
						'<dl><dt>Date:<dt><dd>' + response.ScheduleDate + '</dd>' +
						'<dt>Time:<dt><dd>' + response.ScheduleTime + '</dd>' +
						'<dt>Created By</dt><dd>' + response.CreatorFirstName + ' ' + response.CreatorLastName + '</dd>' +
						'<dt>Details</dt>' +
						'<dd><ul>' +
							'<li>Need: ' + response.Need + '</li>' +
							'<li>Has: ' + response.Has + '</li>' +
						'</ul></dd>' +
						'<dt>Additional Detail:</dt><dd>' +
						    response.Comment + '</dd>' +						
						'<dt>Sport Fact:</dt><dd>' +
						getCalorieBurnedBySport(response.GameTypeId) + '</dd></dl>' +
						'<a href="#foodcalculator" id="btnintake" href="javascript:;" name="btnintake">check my intake</a><br>' +
						'<ul id="participants">' +
						'</ul>' +
						button +
					'</div>'
					);
        var participants = html.find('ul#participants');
        for (var i = 0; i < response.Participants.length; i++) {
            var player = $(
							'<li id="u' + response.Participants[i].UserId + '">' +
								'<img src="' + response.Participants[i].ThumbnailUrl + '" alt="' + response.Participants[i].FirstName + ' ' + response.Participants[i].LastName + '" />' +
								'<a href="' + response.Participants[i].FacebookUrl + '">' + response.Participants[i].FirstName + ' ' + response.Participants[i].LastName + '</a>' +
							'</li>'
							);
            participants.append(player);
        }

        //html.find('a#btnintake').click(moveToIntake);

        if (response.InGame) {
            html.find('a#btnleave').click(leaveGame);
        }
        else {
            html.find('a#btnjoin').click(joinGame);
        }

        gamedetail.children().remove();

        gamedetail.append(html);

    }

    //join the game
    function joinGame(e) {
        if (_currentGameId != 0) {
            var json = new Object();
            json.GameId = _currentGameId;
            json.UserId = _userId;

            sendAJAX('AddParticipant', json, $(e.target));
        }
    }

    //successfully join the game
    function handleAddParticipant(response, target) {
    	var button = $('<a href="javascript:;" id="btnleave" name="btnleave">Can\'t make it</a>');
        button.click(leaveGame);

        var player = $(
						'<li id="u' + response.UserInfo.UserId + '">' +
							'<img src="' + response.UserInfo.ThumbnailUrl + '" alt="' + response.UserInfo.FirstName + ' ' + response.UserInfo.LastName + '" />' +
							'<a href="' + response.UserInfo.FacebookUrl + '">' + response.UserInfo.FirstName + ' ' + response.UserInfo.LastName + '</a>' +
						'</li>'
						);

        target.parents('#play_info').find('ul#participants').append(player);
        target.replaceWith(button);
    }

    //leaving the game
    function leaveGame(e) {
        if (_currentGameId != 0) {
            var json = new Object();
            json.GameId = _currentGameId;
            json.UserId = _userId;

            $('ul#participants').find('#u' + _userId).remove();
            sendAJAX('RemoveParticipant', json, $(e.target));
        }
    }

    //successfully leaving the game
    function handleRemoveParticipant(target) {
    	var button = $('<a href="javascript:;" id="btnjoin" name="btnjoin">Join Game</a>');
        button.click(joinGame);
        target.replaceWith(button);
    }

    //clear food
    function clearfoodClicked(e) {
        myfood.children().remove();
        return false;
    }

    //Loadup the Food Calculator
    function dispatchFoodCalculator(e) {
        var foodintake = '';
        var i = 0;
        for (i = 0; i < myfood.children('a').size(); i++) {
            var temp = $(myfood.children('a')[i]).children('input').val();
            foodintake += temp;
            if (i != myfood.children('a').size() - 1) {
                foodintake += ',';
            }
        }

        if (foodintake != '') {
            $.BadBox({ width: 800, height: 600, iframe: "/badbox/FoodCalculator.aspx?FoodIdArray=" + foodintake });
            return false;
        }

        return false;
    }

    //When gamehistory gets cicked
    function gamehistoryClicked(e) {
        if (_userId != 0) {
            $.BadBox({ width: 500, height: 600, iframe: "/badbox/GameHistory.aspx?UserId=" + _userId });
        }
        return false;
    }

    function gotoPlay(e) {
        //play.ScrollTo(500);
        goToByScroll('play');
        return false;
    }

    function gotoLearn(e) {
        goToByScroll('quiz');
        return false;
    }

    function gotoEat(e) {
        goToByScroll('foodcalculator');
        return false;
    }

    function PopupFAQ() {
        $.BadBox({ width: 800, height: 600, iframe: "/faq/Default.aspx" });
        return false;
    }
    //sendAJAX
    //core AJAX wrapper for sending json objects to a particular webservice method
    //
    //@param action : string : the webservice method to send a request to
    //@param data : object : an object to be serialized an sent as a request to the webservice
    function sendAJAX(action, data, target) {
        $.ajax({
            type: "POST",
            url: "/wsdl/PickupService.svc/" + action,
            data: $.toJSON(data),
            processData: true,
            contentType: "application/json",
            dataType: "json",
            success: function(response, status) {
                //because the webservice isn't sending back what it's responding to, 
                //forward some information about the request to the reponse handler
                dispatchAJAXResponse(action, data, response, target);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                var msg = eval("(" + XMLHttpRequest.responseText + ")").Message;
                alert("Error: " + msg);
            }
        });
    }

    //dispatchAJAXResponse
    //forward the webservice response to the appropriate handler method
    //
    //@param action : string : the webservice method the request was sent to
    //@param request : object : the object sent in the request
    //@param response : object : the object received as a response
    function dispatchAJAXResponse(action, request, response, target) {
        if (response.IsSuccessful) {
            switch (action) {
                case 'GetGameDetailByGameId':
                    handleGetGameDetail(response, target);
                    break;
                case 'AddParticipant':
                    handleAddParticipant(response, target);
                    break;
                case 'RemoveParticipant':
                    handleRemoveParticipant(target);
                    break;

            }
        }
    }


    //get Images for the sports
    function getMapImageByGameTypeId(gametypeid, size) {
        var imageurl;

        switch (gametypeid) {
            case 1:
                imageurl = '../images/sporticon/' + size + '/basketball.png';
                break;
            case 2:
                imageurl = '../images/sporticon/' + size + '/baseball.png';
                break;
            case 3:
                imageurl = '../images/sporticon/' + size + '/football.png';
                break;
            case 4:
                imageurl = '../images/sporticon/' + size + '/tennis.png';
                break;
            case 5:
                imageurl = '../images/sporticon/' + size + '/soccer.png';
                break;
            case 6:
                imageurl = '../images/sporticon/' + size + '/volleyball.png';
                break;
            case 7:
                imageurl = '../images/sporticon/' + size + '/golf.png';
                break;
            case 8:
                imageurl = '../images/sporticon/' + size + '/boxing.png';
                break;
            case 9:
                imageurl = '../images/sporticon/' + size + '/shoe.png';
                break;
            case 10:
                imageurl = '../images/sporticon/' + size + '/hockey.png';
                break;
            case 12:
                imageurl = '../images/sporticon/' + size + '/frisbee.png';
                break;
            case 13:
                imageurl = '../images/sporticon/' + size + '/cycling.png';
                break;
            case 14:
                imageurl = '../images/sporticon/' + size + '/gym.png';
                break;
            case 15:
                imageurl = '../images/sporticon/' + size + '/pingpong.png';
                break;
            default:
                imageurl = '../images/sporticon/' + size + '/trophy.png';
                break;
        }

        return imageurl;
    }

    function getCalorieBurnedBySport(gameTypeId) {
        var ret = '';

        switch (gameTypeId) {
            case 1:
                ret = 'This activity burns 440 calories/hour';
                break;
            case 2:
                ret = 'This activity burns 544 calories/hour';
                break;
            case 3:
                ret = 'This activity burns 544 calories/hour';
                break;
            case 4:
                ret = 'This activity burns 544 calories/hour';
                break;
            case 5:
                ret = 'This activity burns 544 calories/hour';
                break;
            case 6:
                ret = 'This activity burns 272 calories/hour';
                break;
            case 7:
                ret = 'This activity burns 306 calories/hour';
                break;
            case 8:
                ret = 'This activity burns 408 calories/hour';
                break;
            case 9:
                ret = 'This activity burns 590 calories/hour';
                break;
            case 10:
                ret = 'This activity burns 440 calories/hour';
                break;
            case 12:
                ret = 'This activity burns 544 calories/hour';
                break;
            case 13:
                ret = 'This activity burns 590 calories/hour';
                break;
            case 14:
                break;
            case 15:
                ret = 'This activity burns 272 calories/hour';
                break;
            default:
                break;
        }

        return ret;
    }

    function addFoodFromModal(data) {
        var html = $('<a class="foodfromsearch">' +
						'<span>' + data.FoodName + '</span>' +
						'<input type="hidden" value="' + data.FoodId + '" />' +
					'</a>');
        html.click(dispatchRemoveFood);
        $('#myfood').append(html);
        return false;
    }
  	

    function goToByScroll(id) {
        $('html,body').animate({ scrollTop: $("#" + id).offset().top }, 'slow');
       }

       function foodsearchClicked(e) {
       	$.BadBox({ width: 800, height: 600, iframe: "/badbox/SearchFood.aspx" });
       	return false;
       }

       $(document).ready(function() {
           $(".filterbutton").click(dispatchFilterClick);

           foodgroup = $('#foodgroup');
           wheatgroup = $('#wheatgroup');
           vegetablegroup = $('#vegetablesgroup');
           fruitgroup = $('#fruitsgroup');
           diarygroup = $('#diarygroup');
           meatgroup = $('#meatgroup');
           extrasgroup = $('#extrasgroup');
           myfood = $('#myfood');

           $('#foodgroup a').draggable({
               appendTo: 'body',
               helper: 'clone'
           });  //Block that can be dragged

           $('#myfood').droppable({
               accept: '#foodgroup a',
               drop: function(ev, ui) {
                   var temp = ui.draggable.clone();
                   $(temp).appendTo(this);

                   $(temp).click(dispatchRemoveFood)
               }
           });


           $("#splash_faq").slideToggle(0);
           $("#faq").click(function() {
               $("#splash_faq").slideToggle();
           });

           $('#intro_faq').click(function() {
		        $('#splash_faq').slideToggle();
		    });

           //set up event handlers
           $('#menu_create').click(dispatchCreateGameClick);
           $('#btnfoodcalculator').click(dispatchFoodCalculator);
           $('#btnclearfood').click(clearfoodClicked);
           $('#menu_history').click(gamehistoryClicked);

           $('#nav_play').click(gotoPlay);
           $('#nav_learn').click(gotoLearn);
           $('#nav_eat').click(gotoEat);

           $('#dash_play').click(gotoPlay);
           $('#dash_learn').click(gotoLearn);
           $('#dash_eat').click(gotoEat);

           $('#intro_play').click(gotoPlay);
           $('#intro_learn').click(gotoLearn);
           $('#intro_eat').click(gotoEat);


           $('#foodsearch').click(foodsearchClicked);

           eat = $('#eat');
           learn = $('#learn');
           play = $('#play');

           gamedetail = $('#play_info');
           _userId = parseInt($('#hidUserId').val(), 10);
           initialize();
       });

