$(document).ready(function(){

	//  Hitchhiker function for ie6 on some pages
	if((jQuery.browser.msie) && (jQuery.browser.version.indexOf("6.")!=-1)){
		$(".AirportDD").blur(function(){
			$("select").css("visibility","visible");
			});
		}


    var MyItineraryManager = "/_assets/dynamic/Modules/ProfileTools/WS/MyItineraryManager.asmx";
    var loadingHtml = '<div class="loading"><img src="/_assets/images/icons/ajax-loader-longer.gif" /></div>';
//  START OF Alterations to HTML
	$("#MyItineraryPane").prepend('<div id="MyItineraryPaneHeader"></div><div id="MyItineraryPaneSide"><div class="top"></div><div class="mid"></div></div>')
	$("#MyItineraryPane").append('<div id="MyItineraryPaneFooter"><div class="lft"></div><div class="rgt"></div><div class="mid"></div></div>')
	$(".help_window").prepend('<div class="shadowSide"><div class="top"></div><div class="mid"></div></div>')
	$(".help_window").append('<div class="shadowFooter"><div class="lft"></div><div class="rgt"></div><div class="mid"></div></div>')
	if($("#MyItinerary .sign-out strong").html().length>24){
		$("#MyItinerary .sign-out strong").html($(".sign-out strong").html().substring(0,24))
		}
//  END OF Alterations to HTML

//  START OF - Vars
	var MyItineraryPanePaddingBottom=20;
	var MyItineraryPanePositionTop=(parseFloat($("#NavSecondary").css("padding-top"))+$("#NavSecondary").height())+$("#NavSecondary").position().top;
//  END OF - Vars

//  START OF Pre-set Event handlers
	$("#MyItineraryPane .close").click(function(){
	       if($(this).parent().parent().hasClass("my-notes")){
		       	notesupdate();
		       	}
	        close_myitinerary()
    		}); 
	$(".add-to-hotels").click(function(){ 
		add_hotel(this);
    		}); 
	$(".add-to-notes").unbind().click(function(){ 
		add_note(this);
    		});
	$("#MyItineraryPane .saved-hotels .controls .send_mail").unbind().click(function(){ 
		send_hotels_mail();
		}) 
	$("#MyItineraryPane .my-notes .controls .send_mail").unbind().click(function(){ 
		send_notes_mail();
		})
	$("#MyItinerarySignIn .head .close").click(function(){
		$("#MyItinerarySignIn").hide();
		})
	$(".controls .state-closed").click(function(){
		$(".create-brochure-pane").attr("src", "about:blank");
		$(".create-brochure-pane").hide(); 
		expand_controls($(this).parent(".controls"))
		});
	$("#MyItineraryPane .help").click(function(e){show_help($(this),e.pageX,e.pageY);})
	$(".help_window .close_help").click(function(){$(".help_window").hide();})

//  END OF Pre-set event handlers



//  START OF Events

	$("#MyItinerary li.tab a").click(function(){
	
	    // close calender if open
		VH.CAL.OnHideCalendar();

		// close booking form if open
		if ($("#FlyOutBookingForm").length) {
		    $("#FlyOutBookingForm").removeClass("bookTrue").addClass("bookFalse");
		}
		
		// hookup server side stuff first and wait for call backs.
		 if ( $(this).parent().hasClass("recent-searches"))
		 {
		    $(".recent-searches .signed-in").html(loadingHtml);
		    
		     $.getJSON( 
			    $.CreateDotNetRemoteMethodCall(
			        MyItineraryManager,
			        "GetSavedSearches"
			    ),    
			    null,
			    DoShowSavedSearches
			);  
		 }
		 
		  if ( $(this).parent().hasClass("saved-hotels"))
		 {
		     $(".saved-hotels .signed-in").html(loadingHtml);
    		    
		         $.getJSON( 
			        $.CreateDotNetRemoteMethodCall(
			            MyItineraryManager,
			            "GetSavedHotels"
			        ),    
			        null,
			        DoShowSavedHotels
			    );  
		 }
		 
		  if ( $(this).parent().hasClass("my-notes"))
		 {
		   $(".my-notes .signed-in").html(loadingHtml);
    		    
		         $.getJSON( 
			        $.CreateDotNetRemoteMethodCall(
			            MyItineraryManager,
			            "GetNotes"
			        ),    
			        null,
			        DoShowNotes
			    );  
		 }
		 
		 return SetUpFrame(this);
		
		});
//  END OF Events

        var SetUpFrame = function(el){
            
		        $("#MyItineraryPane .MyItineraryPaneInternal .controls .state-closed").show().next(".state-open").hide();
		        $(".saved-hotels-pane").show().next(".create-brochure-pane").hide()
		        $("#MyItineraryPane div.MyItineraryPaneInternal").hide();
		        $("#MyItinerarySignIn").hide();
		        $(".help_window").hide();
		        $("#MyItinerary li.tab a").removeClass("active").removeClass("inactive");
		        $(el).addClass("active").parent().next().children("a").addClass("inactive");
		        $("#MyItineraryPane #MyItineraryPaneHeader").removeClass("hdr-recent-searches").removeClass("hdr-saved-hotels").removeClass("hdr-my-notes").addClass("hdr-"+$(el).parent().attr("class").substring(4,$(el).parent().attr("class").length));
  		        $("#MyItineraryPane div."+$(el).parent().attr("class").substring(4,$(el).parent().attr("class").length)).show();
		        $("#MyItineraryPane").removeClass("full-width").removeClass("full-height")
		        if($("#MyItinerary").hasClass("signed-in") && ($(el).parent().hasClass("saved-hotels") || $(el).parent().hasClass("my-notes"))){
			        $("#MyItineraryPane").addClass("full-width")
			        }
		        if($("#MyItinerary").hasClass("signed-in")){
			        $("#MyItineraryPane").addClass("full-height")
			        }

  		        if($("#MyItineraryPane").hasClass("full-height")){
  			        newHeight=($("body").height()-(MyItineraryPanePositionTop+MyItineraryPanePaddingBottom));
  	  		        $(window).resize(function(){
  	  			        adjust_heights()
  	  			        })
  			        }
		        else{
			        newHeight=200
			        $(window).unbind("resize");
			        }
		        if($("#MyItineraryPane").hasClass("full-width")){
			        newWidth="710px";
			        }
		        else{
			        newWidth=($("#MyItinerary li.tab:last a").position().left + $("#MyItinerary li.tab:last a").width()) - $("#MyItinerary li.tab:first a").position().left;
			        }
		        adjust_heights()
		        $("#MyItineraryPane").css("width",newWidth);
        		
		        if((jQuery.browser.msie) && (jQuery.browser.version.indexOf("6.")!=-1)){
			        $("select").css("visibility","hidden");
			        }
		        $("#MyItineraryPane").show()
		        return false; 
        }
        
        var DoShowSavedSearches = function(response){
            if (response.Success == true)
            {   
                $(".recent-searches .signed-in").html(response.Html);
                $("#MyItineraryPane div.recent-searches .body ul").addClass("recent-searches-list").children("li:even").addClass("even");
                
                $("#MyItineraryPane .help").click(function(e){show_help($(this),e.pageX,e.pageY);})
                $(".help_window .close_help").click(function(){$(".help_window").hide();})
                $("#MyItineraryPane .actions .delete, #MyItineraryPane .actions .search, #MyItineraryPane a.search").click(function(){  
                    // fire it to the server and act on the response.
                    $.getJSON( 
                        $.CreateDotNetRemoteMethodCall(
                                                        MyItineraryManager,
                                                        "SavedSearchProcessor",
                                                        this.id
                                                        ),    
                                                        null,
                                                        DoActionSavedSearches);  
                    $(this).parent().html("Please wait...");
		            }) 
            }
            else
            {        
                FliptoSignedOut();
            }
        };

        var DoActionSavedSearches = function(response){
            if (response.Success == true)
            {
                if(response.Response== "Delete") 
                {
                   $(".recent-searches .number").html("("+response.Properties.Count +")")
                   DoShowSavedSearches(response);
                }
                if(response.Response== "Search") 
                {
                   document.location.href = response.Properties.URL;
                } 
            } 
            else
            {
                // error
            }
        }; 
        
        
        
        
         
         var DoShowSavedHotels = function(response){
            if (response.Success == true)
            {   
                $(".saved-hotels .signed-in").html(response.Html);
                    $(".create-brochure-pane").attr("src", "about:blank");
                    $(".create-brochure-pane").hide();
                    $(".saved-hotels .body").show();
                    adjust_heights();   
                
		  		
		  		
                $("#MyItineraryPane div.saved-hotels .body ul").addClass("saved-hotels-list").children("li:even").addClass("even");
                
                 
                
                $("#MyItineraryPane .saved-hotels .controls .send_mail").unbind().click(function(){ 
                    send_hotels_mail();
                }) 
                
                $("#MyItineraryPane .my-notes .controls .send_mail").unbind().click(function(){ 
                    send_notes_mail();
                })
                
                $("#MyItineraryPane .foot .create_brochure").click(function(){ 
                    $(".saved-hotels .body").hide();
                    $(".create-brochure-pane").attr("src", "/my/ebrochure/default.aspx");
                    $(".create-brochure-pane").show();
                    adjust_heights();   
                     
                })
		
                $("#MyItineraryPane .help").click(function(e){show_help($(this),e.pageX,e.pageY);})
                $(".help_window .close_help").click(function(){$(".help_window").hide();})
                
                $("#MyItineraryPane .actions .delete_hotel, #MyItineraryPane .actions .add_to_brochure, #MyItineraryPane a.search , #MyItineraryPane .select_hotel input").click(function(){  
                    // fire it to the server and act on the response.
                    $.getJSON( 
                        $.CreateDotNetRemoteMethodCall(
                                                        MyItineraryManager,
                                                        "SavedHotelProcessor",
                                                        this.id
                                                        ),    
                                                        null,
                                                        DoActionSavedHotels);   
		            }) 
            }
            else
            {        
                FliptoSignedOut();
            }
        };

        var DoActionSavedHotels = function(response){
            if (response.Success == true)
            {
            
                
                if(response.Response== "Added") 
                {
                   $(".saved-hotels .number").html("("+response.Properties.Count +")");
                   $(".add-to-hotels").parent().html("In your Saved Hotels list.");
                }
                
                 if(response.Response== "Delete") 
                {
                   $(".saved-hotels .number").html("("+response.Properties.Count +")")
                   DoShowSavedHotels(response);
                }
                
                if(response.Response== "Search") 
                {
                   document.location.href = response.Properties.URL;
                } 
            } 
            else
            {
                // error
            }
        }; 
    
    
    function add_hotel(obj){ 
                var id = $(obj).parent()[0].id; 
                $(".add-to-hotels").html("Please wait...");
                $.getJSON( 
                        $.CreateDotNetRemoteMethodCall(
                                                        MyItineraryManager,
                                                        "SavedHotelProcessor",
                                                        "A"+ id
                                                        ),    
                                                        null,
                                                        DoActionSavedHotels);    
    		}; 
    	
    	
        function add_note(obj){   
                 
                var id = $(obj).parent()[0].id; 
                $(".add-to-notes").html("Please wait..." + loadingHtml); 
                $.getJSON( 
                        $.CreateDotNetRemoteMethodCall(
                                                        MyItineraryManager,
                                                        "AddNote",
                                                        document.location.href,
                                                        $.trim($("title").text()),
                                                        getSelectedText()
                                                        ),    
                                                        null,
                                                        DoActionAddNote);    
    		}; 
    	
    	function getSelectedText(){
                if(window.getSelection){
                    return window.getSelection().toString();
                }
                else if(document.getSelection){
                    return document.getSelection();
                }
                else if(document.selection){
                    return document.selection.createRange().text;
                }  
    	}
    	
    	
    	var DoActionAddNote = function(response){ 
            if (response.Success == true)
            {  
           
                    $(".add-to-notes").html("Add to My Notes"); 
                    
                    VH.CAL.OnHideCalendar();
                    
                    $(".my-notes .signed-in").html(loadingHtml); 
	                 $.getJSON( 
		                $.CreateDotNetRemoteMethodCall(
		                    MyItineraryManager,
		                    "GetNotes"
		                ),    
		                null,
		                DoShowNotes
			          );  
			        SetUpFrame($(".my-notes a"));
                    
            }
            else
            {        
                FliptoSignedOut();
            }	 
    	}
    	 
    	 
         var DoShowNotes = function(response){
       
            if (response.Success == true)
            {   
            
                $(".my-notes .signed-in").hide().html(response.Html); 
                $('#MyItineraryNotesEntry').wysiwyg(  
                                {
                                html : '<'+'?xml version="1.0" encoding="UTF-8"?'+
                                '><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'+
                                '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head>'+
                                '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">'+
                                '<link rel="stylesheet" type="text/css" media="screen" href="/_assets/css/myitinerary.css" />'+
                                '</head><body class="inner" style="overflow-x:hidden;font: 75%/125% Arial, Helvetica, sans-serif;margin:0px;padding:0px;">INITIAL_CONTENT</body></html>', 
                                controls : { 
                                    separator04 : { visible : true }, 
                                    insertOrderedList : { visible : true },
                                    insertUnorderedList : { visible : true },
                                    insertImage : { visible : false },
                                    h1mozilla : { visible : false },
                                    h2mozilla : { visible : false },
                                    h3mozilla : { visible : false },
                                    h1 : { visible : false },
                                    h2 : { visible : false },
                                    h3 : { visible : false }, 
                                    separator07 : { visible : false },
                                    separator08 : { visible : false },
                                    separator09 : { visible : false },
                                    removeFormat : { visible : false },
                                    saveSep : { separator : true },
                                    save : {
                                        visible   : true,
                                        exec      : function() { 
							window.notesupdate(  ); 
							$(".save").addClass("save-working");
                                        	},
                                        className : 'save'
	                                } 
                                    }
                                } 
                 );
                $(".my-notes .signed-in").show();
                adjust_heights();    
                 
                 
            }
            else
            {        
                FliptoSignedOut();
            }
        };
 
	
    function delete_item(obj){ 
		return false;
	} 
		
		
	
    var FliptoSignedOut = function()
    {
        $("#MyItineraryPane, #MyItinerary").removeClass("signed-in").addClass("signed-out");  
    }
    	
//  START OF Functions
	function adjust_heights(){
		if($("#MyItineraryPane").hasClass("signed-in")){
//			newHeight=($("body").height()-(MyItineraryPanePositionTop+MyItineraryPanePaddingBottom));
			newHeight=($(window).height()-(MyItineraryPanePositionTop+MyItineraryPanePaddingBottom));
	  		$("#MyItineraryPane").css("height",newHeight);
	  		$("#MyItineraryPane .MyItineraryPaneInternal").css("height",newHeight - 0);
	  		$("#MyItineraryPane .MyItineraryPaneInternal .body").each(function(i){
				var ControlsHeight=0;
				if($("#MyItineraryPane .MyItineraryPaneInternal .body").eq(i).prev("div").hasClass("controls")){
					$("#MyItineraryPane .MyItineraryPaneInternal .controls .state-closed").show().next(".state-open").hide();
					$("#MyItineraryPane .MyItineraryPaneInternal .body").eq(i).prev("div").css("height",30)
					ControlsHeight+=30
					}
				if($("#MyItineraryPane .MyItineraryPaneInternal .body").eq(i).next("div").hasClass("foot")){
					ControlsHeight+=30
					}
				if($("#MyItineraryPane .MyItineraryPaneInternal .body").eq(i).next().next("div").hasClass("foot")){
					ControlsHeight+=30
					}
					
		  		$("#MyItineraryPane .MyItineraryPaneInternal .body").eq(i).css("height",newHeight - 36 - ControlsHeight);
		  		$("#MyItineraryPane .MyItineraryPaneInternal .create-brochure-pane").css("height",newHeight - 68 - ControlsHeight); 
		  		$("#MyItineraryPane .MyItineraryPaneInternal .create-brochure-pane").css("width",$("#MyItineraryPane .MyItineraryPaneInternal .create-brochure-pane").parent().width() - 8); 
		  		
		  		$("#MyItineraryPane .MyItineraryPaneInternal .body div.wysiwyg").css("height",newHeight - 48 - ControlsHeight);
		  		$("#MyItineraryPane .MyItineraryPaneInternal .body div.wysiwyg").css("width",$("#MyItineraryPane .MyItineraryPaneInternal .body div.wysiwyg").parent().width()-12); 
//		  		$("#MyItineraryPane .MyItineraryPaneInternal .body div.wysiwyg").css("height",newHeight - 48 - ControlsHeight-10);
//		  		$("#MyItineraryPane .MyItineraryPaneInternal .body div.wysiwyg").css("width",$("#MyItineraryPane .MyItineraryPaneInternal .body div.wysiwyg").parent().width()-12-10); 
		  		$("#MyItineraryPane .MyItineraryPaneInternal .body #MyItineraryNotesEntryIFrame").css("width",$("#MyItineraryPane .MyItineraryPaneInternal .body #MyItineraryNotesEntryIFrame").parent().width()); 
		  		$("#MyItineraryPane .MyItineraryPaneInternal .body #MyItineraryNotesEntryIFrame").css("height",newHeight - 75 - ControlsHeight);
		  
		  		
	  			})
	  		$("#MyItineraryPane #MyItineraryPaneSide .mid").css("height",newHeight-21);
			}
		}
		
	function expand_controls(obj){
		$("#MyItinerarySignIn").hide();
		$(".help_window").hide();
		$(obj).children(".state-closed").unbind("click");
		$(obj).animate( { height: "0px" } , function(){
			$(this).children(".state-closed").hide().next(".state-open").show();
			$(this).next(".body").animate( { height: "-=30px" } )
			$(this).animate( { height: "+=90px" } )
			// $(this).next(".body").children(".signed-in").children("textarea").animate( { height: "-=60px" } )
			$(this).children(".state-open").eq(0).children(".cancel").click(function(){
				contract_controls(this)
				});
			});
		}

	function contract_controls(obj,sent_mail,send_mail_error,send_mail_error_msg){
		$("#MyItinerarySignIn").hide();
		$(".help_window").hide();
  		$(obj).parent(".state-open").parent(".controls").animate( { height: "0px" } , function(){
			    if(sent_mail){
				    if(send_mail_error){
					    $(this).children(".state-closed").children("span").html(send_mail_error_msg)
					    }
				    else{
					    $(this).children(".state-closed").children("span").html("We've sent that mail for you.  Send another.")
					    }
				    }
			    else
			    {
			        $(this).children(".state-closed").children("span").html("Email to a friend.")
			    }
  			    $(this).children(".state-closed").show().next(".state-open").hide();
  			    $(this).children(".state-closed").css("height","30px")
  			    $(this).children(".state-open").css("height","30px")
  			    $(this).next(".body").animate( { height: "+=30px" } )
  			    $(this).animate( { height: "+=30px" } ) 
			$(".create-brochure-pane").hide(); 
			$(".saved-hotels .body").show();

  			});
		if(!sent_mail){
			$(obj).unbind("click");
			}
		$(".controls .state-closed").click(function(){
			expand_controls($(this).parent(".controls"))
			});
		}
 
	function send_hotels_mail(){
            $(".saved-hotels .controls .input-text").append('<span class="sending">We are trying to send your hotels as a mail.</span>') ;
            $.getJSON( 
                    $.CreateDotNetRemoteMethodCall(
                        MyItineraryManager,
                        "EmailSavedHotels",
                        $(".saved-hotels .controls .input-text input").val()
                        ),    
                        null,
                        send_hotels_email_callback);     
	}
	
	function send_hotels_email_callback(response)
	{
	    $(".saved-hotels .controls .input-text .sending").remove() ;
	    $(".saved-hotels .controls .input-text input").val("");
	    contract_controls($("#MyItineraryPane .saved-hotels .controls .send_mail"),true,!response.Success,response.Response)
//		$(".create-brochure-pane").hide(); 
//		$(".saved-hotels .body").show();
	}
	
	function send_notes_mail(){
            $(".my-notes .controls .input-text").append('<span class="sending">We are trying to send your notes as a mail.</span>') ;
            $.getJSON( 
                    $.CreateDotNetRemoteMethodCall(
                        MyItineraryManager,
                        "EmailNotes",
                        $(".my-notes .controls .input-text input").val()
                        ),    
                        null,
                        send_notes_mail_callback);     
	}
	
	function send_notes_mail_callback(response)
	{
	    $(".my-notes .controls .input-text .sending").remove() ;
	    $(".my-notes .controls .input-text input").val("");
	    contract_controls($("#MyItineraryPane .my-notes .controls .send_mail"),true,!response.Success,response.Response)
	}
		
	function show_help(obj,x,y){ 
		help_on_subject=obj.children("img").attr("alt");
		help_window_html="<p><strong>"+obj.children("img").attr("alt")+"</strong></p>";
		if(help_on_subject.indexOf("Recent Searches")!=-1){
			help_window_html+="<p>When you make a search on this website we store the information here so you can make one-click searches without having to enter all the details again.</p><p>We let you delete searches so do not worry about us ruining your plan for a surprise trip away.</p>";
			}
		else if(help_on_subject.indexOf("Saved Hotels")!=-1){
			help_window_html+="<p>When you visit a hotel you can click on the <em>Add to Saved Hotels</em> button and we will store the details here for quick and easy access so you can come back and find them with a single click.</p><p>We let you delete those hotels so we will not spoil your surprise trip and we give you the ability to send your hotels in an email to help with planning a trip with other people.</p>";
			}
		else if(help_on_subject.indexOf("My Notes")!=-1){
			help_window_html+="<p>You can use the notes section to scribble down bits of information you want to record while looking through the site.  You can also add  pages on virginholidays.co.uk using the <em>Add to My Notes</em> button, type in your own text, copy and paste details from web pages, and we'll save it all for you.</p><p>Then we give you the ability to e-mail your notes to anyone to help with planning a trip with other people.</p>";
			}
		else if(help_on_subject.indexOf("Personal Brochure")!=-1){
			help_window_html+="<p>After selecting a number of hotels we will create a Personal Brochure for you in pdf format.</p><p>This will allow you to save, pass on and print out different options for your holiday personalised to you.</p>";
			}

		$(".help_window .cnt").html(help_window_html);
		newY=(y-($("#wrap").position().top)-$("#MyItineraryPane").position().top)
		if((newY+($(".help_window").height()*2))>($("body").height())){
			newY=$("body").height()-(($(".help_window").height())*2)+40;
			}
		if($("#wrap").css("margin-left")!="auto"){
			newX=x-($("#wrap").position().left)-(parseFloat($("#wrap").css("margin-left")))-$("#MyItineraryPane").position().left;
			}
		else{
			newX=x-($("#wrap").position().left)-$("#MyItineraryPane").position().left;
			}
		content_width_help = ( ( $("#MyItineraryPane").width() + $(".help_window").width() ) - ( $("#MyItineraryPane").width() - $(obj).position().left ) ) + $("#MyItineraryPane").position().left;
		window_width_mod = Math.floor((($("body").width()-$("#wrap").width())/2)+$("#wrap").width());
		if((jQuery.browser.msie) && (jQuery.browser.version.indexOf("6.")!=-1)){
			$(".help_window").css("left",40);
			}
		else if( (window_width_mod > (content_width_help+16))){
			$(".help_window").css("left",newX);
			}
		else{
			$(".help_window").css("left",8+(newX-$(".help_window").width()));
			}
		$(".help_window").css("top",newY);
		$(".help_window").show();
		return false;
		}
	function hide_help(obj){
		$(".help_window").hide();
		return false;
		}


    //  END OF Functions


	});

	function close_myitinerary(){
		$("#MyItinerary li.tab a").removeClass("active").removeClass("inactive");
		$("#MyItineraryPane").hide();
		if((jQuery.browser.msie) && (jQuery.browser.version.indexOf("6.")!=-1)){
			$("select").css("visibility","visible");
			}
		$(".saved-hotels .controls .state-closed span").html('Email my hotels to a friend.')
		$(".my-notes .controls .state-closed span").html('Email my notes to a friend.')
		}
		
    function notesupdate()
    { 
        if ($("#MyItineraryNotesEntryIFrame").length > 0)
        {
        $.post(  $.CreateDotNetRemoteMethodCall(
                    "/_assets/dynamic/Modules/ProfileTools/WS/MyItineraryManager.asmx",
                    "UpdateNotes",
                    "payload"
                    ),    
                    {payload: $($("#MyItineraryNotesEntryIFrame").document()).find("body").html() },
                    function (){ 
			$(".save").removeClass("save-working");
                    	}
             );     
        } 
    }
