
/**
 * Travel Pack pop-up
 *
 * @created Mon Aug 20 2008 08:00:09 EDT 
 * @v2 - last edited Fri Aug 29 2008 10:11:50 EDT
 * @return void
 * @author Dan Mall
 * @corrected and implemented more functionally by Matt MacGillivray
 **/

$(document).ready(function()
{
    TravelPack_Attach_Events();
});


/**
 * Attach all popup events
 */
function TravelPack_Attach_Events()
{
	var packCount = 0;
	
	$('.add a').click(function(){
		packCount++;	
		
		// is this a 'travelpack' we are trying to add to our profile?
		if($(this).parents('.travel_pack').size() || $(this).parents('.single-tpk').size() || $(this).parents('.travel_pack_header').size() || $(this).parents('.CopyTPK').size()){ 
		
		    // find the parent to add the travelpack to.
		    var addButton = $(this);
			var addButtonParent = $(this).parent();		
	
	        // if we already have a popup open, close it...
	        // TODO - I think this is flawed..
			if($(addButtonParent).next().hasClass('pop_up')) { 
				closePopUp($(addButtonParent).next());			
				//closePopUp($(this).parent().next());
				
			} else {
			    // get the current travelpack id, which is encoded in the 'href'
			    // Example: <a href="#<travelpackid>"/> where <travelpackid> is the numeric travelpackid
			    //var travelPackId = addButtonParent.text();
			    var travelPackId = $(addButton).attr('href');
			    if (travelPackId != null && travelPackId.length > 0) {
			        travelPackId = travelPackId.substring(1);
			    }
			    
			    // try to duplicate this travelpack
                TravelPack_Duplicate_Display(addButtonParent, packCount, travelPackId);
                
				// animate open - should this be here?
				//addButtonParent.next().hide();					
				//addButtonParent.next().slideDown("normal");
			}
		
		}else{ //large add button
	
			var addButtonParent = $(this).parent();		
			var addButton = $(this);
			
		
			if($(addButtonParent).next().hasClass('pop_up')) { 
				closePopUp($(addButtonParent).next());			
				//closePopUp($(this).parent().next());
			}else{
			    var itemType = "";
			    var itemId = "";
			    var defaultSelectedId = "";
			    
			    // var itemInfoArray = addButtonParent.text().split(',');
			    // get the current place/media id, which is encoded in the 'href'
			    // Example Place: <a href="#place,<placeid>"/> where <placeid> is the numeric placeid
			    // Example Media: <a href="#media,<placeid>"/> where <mediaid> is the numeric mediaid
			    var itemInfoArray = $(addButton).attr('href');
			    if (itemInfoArray != null)
			    {
			        itemInfoArray = itemInfoArray.split(',');
			        if (itemInfoArray.length > 0) {
			            itemType = itemInfoArray[0].substring(1);
    			        itemId = itemInfoArray[1];
    			        if (itemInfoArray.length >= 2) {
    			            defaultSelectedId = itemInfoArray[2];
    			        }
			        }
			    }
			    TravelPack_Add_Display(addButtonParent, packCount, itemType, itemId, defaultSelectedId);
				
				// animate open
				/**
				addButtonParent.next().hide();					
				addButtonParent.next().slideDown("normal");
				**/
			}
		}
		return false;
	});
}


/**
 * Generic method that closes a popup..
 */
function closePopUp(popup){
	// animate closed
	popup.slideUp("fast", function(){ $(this).remove(); });
	return false;
}

/**
 * Clean the residual popups.
 */
function cleanUpPopUps(packDiv) {
    if(packDiv.next().hasClass('pop_up')) {
        packDiv.next().remove(); // remove the previous popup..  this is bad.. 
    }
}


/**
 * TRAVELPACK Dropdown.
 * User is not logged into the system, so display the 'login' form.
 *
 * TODO - add refering url.. so login page will return you to this page.
 */
function TravelPack_NotLoggedIn(packDiv, packCount) {
    cleanUpPopUps(packDiv);
    packDiv.after('<div class="pop_up"><h3>You need to be a registered user to create and save Travel Packs. <a href="/Register.aspx?ReturnUrl=' + encodeURIComponent(location.href) + '">Register</a> or <a href="/Login.aspx?ReturnUrl=' + encodeURIComponent(location.href) + '">Login</a>.</h3><a href="#" onclick="return closePopUp($(this).parent());" class="button" style="color: #fff;">Close</a></div>');	
}

/**
 * TRAVELPACK Dropdown.
 * User is logged in to the system, so we display the 'save to my profile' dropdown.
 */
function TravelPack_Duplicate_Display_LoggedIn(packDiv, packCount, travelPackId) {
    cleanUpPopUps(packDiv);
    
    // add text field for new travel pack
    packDiv.after('<div class="pop_up"><h3>Save this Travel Pack in my profile:</h3><p><label for="title' + packCount + '">Title:</label><input id="title' + packCount + '" type="text" class="new_tpk" name="" /></p><div><a href="#" onclick="return closePopUp($(this).parent().parent());" class="button" style="margin-left: 2px; color: #fff;">Cancel</a><a href="#" class="button addbutton" style="color:#fff;">Make it Mine</a></div></div>');	
    
    // handler for submission
	$('.pop_up .addbutton').click(function(){
	
		/* -----   INSERT AJAX CHECK HERE TO SEE IF TRAVEL PACK ALREADY EXISTS ----- */

		if($('#title' + packCount).val() == ""){
			$(this).prev('p').before('<p class="error">Please add a title</p>');
		}else{
            TravelPack_Duplicate_CreatePack(packDiv, packCount, travelPackId, $('#title' + packCount).val());
		}
		return false;
    });					
}

/**
 * TRAVELPACK Dropdown.
 * Erroradd.
 *
 * TODO - add refering url.. so login page will return you to this page.
 */
function TravelPack_Error(packDiv) {
    cleanUpPopUps(packDiv);
    packDiv.after('<div class="pop_up"><h3>Sorry, we had a problem processing your request.  Please try again!</h3><a href="#" onclick="return closePopUp($(this).parent());" class="button" style="color: #fff;">Close</a></div>');
}

/**
 * TRAVELPACK Dropdown.
 * Processing message...
 */
function TravelPack_Waiting(packDiv) {
    cleanUpPopUps(packDiv);
    packDiv.after('<div class="pop_up"><h3>Loading... Please wait.</h3></div>');
}


/**
 * TRAVELPACK Dropdown.
 *
 * User successfully duplicated a travelpack.
 */
function TravelPack_Duplicate_CreatePack_Success(packDiv, packCount, title, travelPackUrl)
{
    cleanUpPopUps(packDiv);
    packDiv.after('<div class="pop_up"><h3>Just created your new <a href="' + travelPackUrl + '">' + title  + '</a> Travel Pack</h3><a href="#" onclick="return closePopUp($(this).parent());" class="button" style="color:#fff;">Close</a></div>');
}


/**
 * Start the duplication process..
 */
function TravelPack_Duplicate_Display(packDiv, packCount, travelPackId)
{
    TravelPack_Waiting(packDiv);
    
    $.ajax({

        type: "POST",
        url: "/webservice/FlashService.asmx/GetUserID",
        data: "",
        contentType: "application/json; charset=utf-8", 
        dataType: "xml",

        success: function(xhr, status) {
            // get the userid
            var userid = -1;
            $(xhr).find("int").each(function() {
                userid = $(this).text();
            });
            if (userid > 0) {
                TravelPack_Duplicate_Display_LoggedIn(packDiv, packCount, travelPackId);
            } else {
                TravelPack_NotLoggedIn(packDiv, packCount);
            }
        },

        error: function(xhr, status, error) {
            TravelPack_Error(packDiv);
        },

        complete: function(xhr, status) {
            // do nothing..
        }

    });
}


/**
 * Duplicate a the given travelpack, using the title provided.
 */
function TravelPack_Duplicate_CreatePack(packDiv, packCount, travelPackId, title)
{
    TravelPack_Waiting(packDiv);
    $.ajax({

        type: "POST",
        url: "/webservice/FlashService.asmx/TravelPacksDuplicate",
        data: "travelpackid=" + travelPackId + "&title=" + title,
        contentType: "application/x-www-form-urlencoded; charset=utf-8", 
        dataType: "xml",

        success: function(xhr, status) {
            var newTravelPackId = -1;
            $(xhr).find("rsp").each(function() {
                // make sure the service succeeded
                if ($(this).attr("stat") == "ok") {
                    newTravelPackId = $(this).attr("travelpackid");
                    newTravelPackUrl = $(this).attr("travelpackurl");
                }
            });
            
            if (newTravelPackId > 0) {
                TravelPack_Duplicate_CreatePack_Success(packDiv, packCount, title, newTravelPackUrl);
            } else {
                TravelPack_Error(packDiv);
            }
        },

        error: function(xhr, status, error) {
            TravelPack_Error(packDiv);
        },

        complete: function(xhr, status) {
            // do nothing..
        }

    });

}


/**
 * TRAVELPACK Dropdown
 * Add to travelpack dropdown for places and media.
 */
function TravelPack_Add_Display(packDiv, packCount, itemType, itemId, defaultSelectedId) 
{
    TravelPack_Waiting(packDiv);
    
    $.ajax({

        type: "POST",
        url: "/webservice/FlashService.asmx/GetUserID",
        data: "",
        contentType: "application/json; charset=utf-8", 
        dataType: "xml",

        success: function(xhr, status) {
            // get the userid
            var userid = -1;
            $(xhr).find("int").each(function() {
                userid = $(this).text();
            });
            if (userid > 0) {
                TravelPack_Add_Display_LoggedIn(packDiv, packCount, itemType, itemId, defaultSelectedId);
            } else {
                TravelPack_NotLoggedIn(packDiv, packCount);
            }
        },

        error: function(xhr, status, error) {
            TravelPack_Error(packDiv);
        },

        complete: function(xhr, status) {
            // do nothing..
        }

    });
}


/**
 * TRAVELPACK Dropdown
 * Add to travelpack dropdown for places and media.
 */
function TravelPack_Add_Display_LoggedIn(packDiv, packCount, itemType, itemId, defaultSelectedId)
{
    $.ajax({

        type: "POST",
        url: "/webservice/FlashService.asmx/TravelPacksGet",
        data: "",
        contentType: "application/x-www-form-urlencoded; charset=utf-8", 
        dataType: "xml",

        success: function(xhr, status) {
        
            $(xhr).find("rsp").each(function() {
            
                // if we got a list of travelpacks, display the dropdown..
                if ($(this).attr("stat") == "ok") {
                    TravelPack_Add_Display_LoggedIn_DropDown(packDiv, packCount, $(this), itemId, itemType, defaultSelectedId);
                   
                // error, so lets deal with it 
                } else {
                    $(this).find("err").each(function() {
                    
                        if ($(this).attr("code") == "2") {
                            TravelPack_NotLoggedIn(packDiv, packCount);
                            
                        } else {
                            TravelPack_Error(packDiv);
                        }
                    });
                }
            });
        },

        error: function(xhr, status, error) {
            TravelPack_Error(packDiv);
        },

        complete: function(xhr, status) {
            // do nothing..
        }

    });
}



/**
 * TRAVELPACK Dropdown.
 * Success - create the dropdown..
 */
function TravelPack_Add_Display_LoggedIn_DropDown(packDiv, packCount, xmlResponse, itemId, itemType, defaultSelectedId) {
    // before we display the dropdown, make sure the other popups are clean..
    cleanUpPopUps(packDiv);
    
    // default option tells the user to select something..
    var options = '';'<option>Select a Travel Pack</option>';
	var createText = 'Create new&hellip;';
	var tpCount = 0;
   
    // iterate over the xmlResponse to build the list of options..
    $(xmlResponse).find("travelpack").each(function() {
        if (defaultSelectedId !== undefined && $(this).attr("travelpackid") == defaultSelectedId) 
        {
            options += '<option value="' + $(this).attr("travelpackid") + '" selected>' + $(this).attr("title") + '</option>';
        } else {
            options += '<option value="' + $(this).attr("travelpackid") + '">' + $(this).attr("title") + '</option>';
        }
        tpCount++;
    });
   
    // create the dropdown
    packDiv.after('<div class="pop_up"><p><label for="options' + packCount + '">Add to:</label><select id="options' + packCount + '">' + options + '<option style="font-weight: bold">' + createText + '</option></select></p><div><a href="#" onclick="return closePopUp($(this).parent().parent());" class="button" style="margin-left: 2px; color: #fff;">Cancel</a><a href="#" class="button addbutton" style="color: #fff;">Add</a></div></div>');	
    
    
    // case: this user has existing travepacks, let them click 'add' by default
    if (tpCount > 0) {
    
			// handler for submission - use case: user doesn't change
			$('.pop_up .addbutton').click(function(){
				/* -----   INSERT CONDITIONAL: AJAX CHECK TO SEE IF THE ITEM IS ALREADY IN THE TRAVEL PACK ----- */

                // do not reload if there was no defaultselected travelpack, OR, the selected value isn't the same as the default
                if (defaultSelectedId === undefined || defaultSelectedId !== $('#options' + packCount).val()) {
			        TravelPack_Add_ExistingPack(packDiv, packCount, $('#options' + packCount + ' :selected').text(), $('#options' + packCount).val(), itemType, itemId, false);
                } else {
			        TravelPack_Add_ExistingPack(packDiv, packCount, $('#options' + packCount + ' :selected').text(), $('#options' + packCount).val(), itemType, itemId, true);
                }
				return false;
			});
    
    // case: otherwise, this user has no travelpacks, so display the 'create new' field by default
    } else {
        // use case: 0 travelpacks, so display the 'add new' input field by default.
	    //packDiv.after('<p><label for="title' + packCount + '">Title:</label><input id="title' + packCount + '" type="text" class="new_tpk" name="" /></p>');								
		if($('.pop_up select').parent().next().get(0).tagName != 'P'){ // and if a text input isn't already there
		    $('.pop_up select').parent().after('<p><label for="title' + packCount + '">Title:</label><input id="title' + packCount + '" type="text" class="new_tpk" name="" /></p>');								
		}
	    
		// handler for submission
		$('.pop_up .addbutton').click(function(){
		    TravelPack_Add_NewPack(packDiv, packCount, $('#title' + packCount).val(), itemId, itemType);
			return false;
		});
    }
    
    
	// handler for select menu
	$('.pop_up select').change(function() {
	
	    // user selects 'create new'						
		if($(this).val() == ($(this).children('option').eq($(this).children('option').size()-1).html())){ // if the user selects "Create new..."						
			if($(this).parent().next().get(0).tagName != 'P'){ // and if a text input isn't already there
				$(this).parent().after('<p><label for="title' + packCount + '">Title:</label><input id="title' + packCount + '" type="text" class="new_tpk" name="" /></p>');								
			}
			
			// handler for submission
			$('.pop_up .addbutton').unbind('click'); // remove the old function before adding the new one.
			$('.pop_up .addbutton').click(function(){
			
			    TravelPack_Add_NewPack(packDiv, packCount, $('#title' + packCount).val(), itemId, itemType);
				return false;
			});
			
	    // user selects a travelpack..
		}else{ // if the user selects anything other than "Create new..."						
			if($(this).parent().next().get(0).tagName == 'P'){ // and if the text input is still there
				$(this).parent().next().remove();
			}
		
			// handler for submission
			$('.pop_up .addbutton').unbind('click'); // remove the old function before adding the new one.
			$('.pop_up .addbutton').click(function(){
				/* -----   INSERT CONDITIONAL: AJAX CHECK TO SEE IF THE ITEM IS ALREADY IN THE TRAVEL PACK ----- */

			    TravelPack_Add_ExistingPack(packDiv, packCount, $('#options' + packCount + ' :selected').text(), $('#options' + packCount).val(), itemType, itemId, false);
				return false;
			});
		}
	});					
}


/**
 * TRAVELPACK Dropdown.
 *
 * Add the given itemid and itemtype to a new travelpack, named 'title'.
 */
function TravelPack_Add_NewPack(packDiv, packCount, title, itemId, itemType)
{
    // before we display the dropdown, make sure the other popups are clean..
    //cleanUpPopUps(packDiv);
    TravelPack_Waiting(packDiv);
    
    var urlToCall = "";
    var dataToPass = "";
    if ("place" == itemType) {
        urlToCall = "/webservice/FlashService.asmx/TravelPacksCreateAndAddPlace";
        dataToPass = "title=" + title + "&placeid=" + itemId;
    } else {
        urlToCall = "/webservice/FlashService.asmx/TravelPacksCreateAndAddMedia";
        dataToPass = "title=" + title + "&mediaid=" + itemId;
    }
    $.ajax({

        type: "POST",
        url: urlToCall,
        data: dataToPass,
        contentType: "application/x-www-form-urlencoded; charset=utf-8", 
        dataType: "xml",

        success: function(xhr, status) {
            var newTravelPackId = -1;
            var newTravelPackUrl = "";
            $(xhr).find("rsp").each(function() {
                // make sure the service succeeded
                if ($(this).attr("stat") == "ok") {
                    newTravelPackId = $(this).attr("travelpackid");
                    newTravelPackUrl = $(this).attr("travelpackurl");
                }
            });
            
            if (newTravelPackId > 0) {
                TravelPack_Add_Success(packDiv, packCount, title, newTravelPackUrl, false);
            } else {
                TravelPack_Error(packDiv);
            }
        },

        error: function(xhr, status, error) {
            TravelPack_Error(packDiv);
        },

        complete: function(xhr, status) {
            // do nothing..
        }

    });
}



/**
 * TRAVELPACK Dropdown.
 *
 * User successfully duplicated a travelpack.
 */
function TravelPack_Add_Success(packDiv, packCount, title, travelPackUrl, reload)
{
    if (reload == true) {
        window.location.reload(true);
    } else {
        cleanUpPopUps(packDiv);
        packDiv.after('<div class="pop_up"><h3>Added to the <a href="' + travelPackUrl + '">' + title  + '</a> Travel Pack</h3><a href="#" onclick="return closePopUp($(this).parent());" class="button" style="color: #fff">Close</a></div>');
    }
}


/**
 * TRAVELPACK Dropdown.
 *
 * Figure out which type of item we are adding, then add it to the existing pack.
 */
function TravelPack_Add_ExistingPack(packDiv, packCount, title, travelPackId, itemType, itemId, reload) {
    // before we display the dropdown, make sure the other popups are clean..
    //cleanUpPopUps(packDiv);
    TravelPack_Waiting(packDiv);
    
    if ("place" == itemType) {
        TravelPack_Add_ExistingPack_Place(packDiv, packCount, title, travelPackId, itemId, reload);
    } else {
        TravelPack_Add_ExistingPack_Media(packDiv, packCount, title, travelPackId, itemId, reload);
    }
}

/**
 * TRAVELPACK Dropdown.
 *
 * Add the given itemid and itemtype to a new travelpack, named 'title'.
 */
function TravelPack_Add_ExistingPack_Media(packDiv, packCount, title, travelPackId, mediaId, reload)
{
    $.ajax({

        type: "POST",
        url: "/webservice/FlashService.asmx/TravelPacksAddMedia",
        data: "travelpackid=" + travelPackId + "&mediaid=" + mediaId,
        contentType: "application/x-www-form-urlencoded; charset=utf-8", 
        dataType: "xml",

        success: function(xhr, status) {
            var travelPackUrl = "";
            $(xhr).find("rsp").each(function() {
                // make sure the service succeeded
                if ($(this).attr("stat") == "ok") {
                    travelPackUrl = $(this).attr("travelpackurl");
                    TravelPack_Add_Success(packDiv, packCount, title, travelPackUrl, reload);
                } else {
                    TravelPack_Error(packDiv);
                }
            });
        },

        error: function(xhr, status, error) {
            TravelPack_Error(packDiv);
        },

        complete: function(xhr, status) {
            // do nothing..
        }

    });
}


/**
 * TRAVELPACK Dropdown.
 *
 * Add the given place to the travelpack
 */
function TravelPack_Add_ExistingPack_Place(packDiv, packCount, title, travelPackId, placeId, reload)
{
    $.ajax({

        type: "POST",
        url: "/webservice/FlashService.asmx/TravelPacksAddPlace",
        data: "travelpackid=" + travelPackId + "&placeid=" + placeId,
        contentType: "application/x-www-form-urlencoded; charset=utf-8", 
        dataType: "xml",

        success: function(xhr, status) {
            var travelPackUrl = "";
            $(xhr).find("rsp").each(function() {
                // make sure the service succeeded
                if ($(this).attr("stat") == "ok") {
                    travelPackUrl = $(this).attr("travelpackurl");
                    TravelPack_Add_Success(packDiv, packCount, title, travelPackUrl, reload);
                } else {
                    TravelPack_Error(packDiv);
                }
            });
        },

        error: function(xhr, status, error) {
            TravelPack_Error(packDiv);
        },

        complete: function(xhr, status) {
            // do nothing..
        }

    });
}







