

















var inspireClicked = false;
var plannerCalls = 0;
var changes = 0;
(function($) {


$.ti.panel = $.prototype = {
	//panel snippets
    panelOpen: false,

    promos: false,

    locale: 'int',

	activityDragStarted: 'no',

	datesChanged:	'not_changed',

	tripStarted:	false,

    html:   $([	'<div id="itPanel">',
                    '<div id="panelToggler"><img src="/shared/resource/images/itinerary_planner/us/tabs/panel-tab.png" height="108" alt="Show panel" /></div>',
                    '<div id="panelContent" class="content">',
                        '<div id="bagContainer" class="bag-container">',
                            '<div id="userInfo">',
                                '<p id="userName"></p>',
                                '<ul class="loginWrapper">',
                                    '<li><a class="call-to-action" id="logIn"></a></li>',
                                '</ul>',
                            '</div>',
                            '<h2 id="panelTitle"><img src="/shared/resource/images/itinerary_planner/us/furniture/trip-planner.png" height="28" alt="Trip Planner" /></h2>',
                            '<h3 id="tripName"></h3>',
                            '<form action="" method="" id="categories">',
                                '<label for="showMe">Show me:</label>',
                                '<select id="showMe">',
                                    '<option>You have no items</option>',
                                '</select>',
                            '</form>',
                            '<div class="bagKey">',
                                '<h4>Your items</h4>',
                                '<p id="bagStatus"><span id="currentBagView">0</span> of <span id="bagSize">0</span></p>',
                            '</div>',
                            '<div id="bagWrapper">',
                                '<div class="bag-nav" id="bagUpContainer">',
                                    '<img id="bagUp" class="up disabled" src="/shared/resource/images/itinerary_planner/buttons/bag-nav.png" alt="previous" height="52" />',
                                '</div>',
                                '<div id="bagClip">',
                                    '<ul id="theBag" class="identify">',
                                        '<li class="empty"></li>',
                                        '<li class="empty"></li>',
                                        '<li class="empty"></li>',
                                        '<li class="empty"></li>',
                                    '</ul>',
                                '</div>',
                                '<div class="bag-nav" id="bagDownContainer">',
                                    '<img class="down disabled" id="bagDown" src="/shared/resource/images/itinerary_planner/buttons/bag-nav.png" alt="previous" height="52" />',
                                '</div>',
                            '</div>',
                            '<div id="add-to-bag">',
                                '<input type="text" value="Add your own item" id="addYourOwn" />',
								'<input type="submit" value="" id="addYourOwnSubmit" />',
                            '</div>',
                        '</div>',
                    '</div>',
                '</div>'
        ].join('')),

		renderPanel : function() {

   		//$.getScript('/shared/resource/js-new/jquery.pngFix.js');

        var wrapper, toggleImage;

		// Detect if the itinerary planner wrapper already exist.
        if ($('#itWrapper').length < 1) {
			wrapper = $('<div class="itWrapper"></div>');

			if(document.getElementById('headerWrapper')) {
			    $('#headerWrapper').wrap(wrapper);
			} else {
			    $('.page').wrapInner(wrapper);
			}
        } else {
        	$('#itWrapper').addClass('itWrapper');
        }
		this.html.appendTo($('.itWrapper'));

		// Add panel opening event
		toggleImage = $('img:first', '#panelToggler');

        $('#panelToggler').click(function() {
			switch($.ti.panel.panelOpen){
				case true:  $('#panelContent').trigger('PANEL_CLOSING');
                            $($.ti.panel.html).animate({
								width: "218px"
							}, 1000, 'easeInBack');
							$(toggleImage).css({"left": "0px"});
							$.ti.panel.panelOpen = false;
                           	 //need to show/hide the select dropdowns for IE6 bug
                            $('#finder select, select#title').fadeIn('slow');
							break;
				case false:	$('html, body').animate({ scrollTop: 0 }, 500);
							$($.ti.panel.html).animate({
								width: "992px"
							}, 1000, 'easeOutBack', function() {
                                                        $('#panelContent').trigger('PANEL_OPENED');
                                                    });
							$(toggleImage).css({"left": "-24px"});
							if ($.ti.bag.unopened) $.ti.bag.unopened = false;
							$.ti.panel.panelOpen = true;
                            // Check if the calender has any date errors.
                            if($.ti.createTripCalendar.hasErrors) {
                                $.ti.messages.hasErrors();
                            }
							// Check if the calender has any product errors.
                            if($.ti.createTripCalendar.hasProductErrors) {
                                $.ti.messages.hasProductErrors();
                            }

                            //need to show/hide the select dropdowns for IE6 bug
                            $('#finder select, select#title').fadeOut('slow');
							break;
			}
		});

		this.getLocale();
		this.getTripData();

		$.ti.panelContent.setUpContent();
		$.ti.bag.init();
		this.setUpAddYourOwn();
		this.setUnload();
		// Calender activity item events intialisation
		$.ti.createCalendarActivity.events();

        //IE6 png fixes
        if ($.browser.msie && $.browser.version.substr(0,1)<7) {
            $('h2#panelTitle').pngFix();
            $('#panelToggler img').attr('src','/shared/resource/images/itinerary_planner/tabs/panel-tab.gif');
    	}





	},

    setUnload: function() {
        window.onunload = function() {
            // Check that trip has activities - if so save

            if($.ti.tripData.trip.tripActivities) {
				// write timestamp to json and cookie
				var timeStamp = new Date().toString();
				$.ti.tripData.trip.dataPostTime = timeStamp;
                //$.ti.tripData.trip.selectedCategory = 'Accommodation';
                //$.ti.tripData.trip.selectedCategory = 'all';
				$.ti.cookie.setCookie('ItineraryPlanner', $.ti.tripData.trip.id, $.ti.tripData.trip.dataPostTime);
                $.ti.ajax.postData('/us/trip/', $.ti.tripData);
            }
        }
    },

    // ToDo: duplicating this in choose-locale.js - move to utils when consolidting code?
    getLocale: function() {
        var locale =  document.location.pathname.split('/');
        this.locale = locale[1];
    },

	setUpAddYourOwn: function() {
		$('#itPanel').tiClearInputs();
		$('#addYourOwn').focus(function(){
            $.ti.nag.kill();
            $.ti.panel.openAddYourOwn();
            $(this).blur();
        });


		$('#addBookmark').click(function() {
/*			var text = document.title + '\r\n' + window.location.href + '\r\n';
			$.ti.panel.openAddYourOwn(text); */

            $.ti.panel.openAddYourOwnWithLink(document.title, window.location.href);
		});
	},

    openAddYourOwnWithLink: function(text, link) {
        text = text || '';
        link = link || '';

        $.ti.popup.overlay();
        var html = $(["<div id='activityDetail' style='left: " + Math.round(($(document).width()/2) - 210) + "px'}}'>",
                         "<span class='close-detail'></span>",
                         "<div class='content UserGenerated'>",
                            "<div class='info'>",
                               "<textarea id='addYourOwnContent'>" + text + "</textarea>",
                               "<a href='" + link + "' target='_blank'>view this page</a>",
	                           "<input height='22' type='image' width='102' src='/shared/resource/images/itinerary_planner/us/buttons/add-to-trip.png' id='addYourOwnSave' style='float: right' />",
                            "</div>",
                         "</div>",
                      "</div>"].join(''));

        $(document.body).prepend(html);

        $('#addYourOwnContent').focus();
        $('#addYourOwnSave').click(function() {
            // If they are not a reviewer...
            if ($.ti.tripData.trip.role !== 'R') {
				if((document.getElementById('addYourOwnContent').value.match(/[^\d\s]/)) && ( document.getElementById('addYourOwnContent').value != document.getElementById('addYourOwn').defaultValue) ) {
                    var activity = {
                        id: 0,
                        actCategory: "User Generated",
                        actName: document.getElementById('addYourOwnContent').value,
                        actCity: '',
                        actUrl: link
                    };
                    $.ti.bag.add(activity, true);
		            $.ti.ajax.postData('/us/trip/', $.ti.tripData);
                }
            } else {
                $(this).blur();
                $.ti.messages.notForReviewer();
            }

            $('#overlay').remove();
            $('#activityDetail').remove();
        });
    },

	openAddYourOwn: function(text) {
		text = text || '';

		// Append overlay
		$.ti.popup.overlay();
		var html = $(['<div id="activityDetail" style="left:' + Math.round(($(document).width()/2) - 210) + 'px">',
			'<span class="close-detail"></span>',
			'<div class="content UserGenerated">',
				'<div class="info">',
					'<textarea id="addYourOwnContent">' + text + '</textarea>',
					'<input height="22" type="image" width="102" src="/shared/resource/images/itinerary_planner/us/buttons/add-to-trip.png" id="addYourOwnSave" />',
				'</div>',
			'</div>',
		'</div>'
		].join(''));
		// Append detail popup
		$(document.body).prepend(html);

        // TODO: REMOVE
        //if (typeof(console) != 'undefined')
        //    console.log("Focusing addYourOwnContent");

		$('#addYourOwnContent').focus();

		$('#addYourOwnSave').click(function() {
			// If they are not a reviewer
			if($.ti.tripData.trip.role !== 'R') {
				// Check that something other than whitespace or the default message exists.
				if((document.getElementById('addYourOwnContent').value.match(/[^\d\s]/)) && ( document.getElementById('addYourOwnContent').value != document.getElementById('addYourOwn').defaultValue) ) {
					var activity = {
					id: 0,
					actCategory: "User Generated",
					actName: document.getElementById('addYourOwnContent').value,
					actCity: ''
					};
					$.ti.bag.add(activity, true);
		            $.ti.ajax.postData('/us/trip/', $.ti.tripData);
				}
			} else {
				$(this).blur();
				$.ti.messages.notForReviewer();
			}

			$('#overlay').remove();
			$('#activityDetail').remove();
		});
	},


    getTripData: function() {
        var tripId, tripCookie, url, params, paramLength, count, tripKey;

        tripCookie = $.ti.cookie.getCookie('ItineraryPlanner');
        if(tripCookie) {
            tripId = tripCookie[1];
        }

        // Check url for deeplinking
        url = (location.href).split('?');
        if(url[1]) {
            params = url[1].split('&');
            paramLength = (params.length);

            for(count = 0; count < paramLength; count += 1) {

                // Check tripId
                if(params[count].match('tripId')) {
                    tripId = params[count].split('=');
                    if (tripId.length > 1) {
                        tripId = tripId[1];
                    }
                }
                // Check tripKey
                if(params[count].match('tripKey')) {
                    tripKey = params[count].split('=');
                    if (tripKey.length > 1) {
                        tripKey = tripKey[1];
                        tripId += '&tripKey=' + tripKey;
                    }
                }
            }
        }

        $.ti.ajax.getJson('/' + this.locale + '/trip/?tripId=' + tripId,  $.ti.panel.saveTripAndPromos, $.ti.panel.useTripData);
    },


    // To be called once trip data has arrived - the callback from getTripData JSON request
    useTripData: function() {

		// If trip data now exists then use it otherwise make a fresh call for the trip data
		if( $.ti.tripData ){

			// check to see that trip data is current and that unload saving is not in progress
			//if( !$.ti.tripData.trip.dataPostTime ||
            //    $.ti.tripData.trip.dataPostTime == "null"  ||
            //    !$.ti.cookie.getCookie('ItineraryPlannerTimeStamp') ||
            //    ($.ti.cookie.getCookie('ItineraryPlannerTimeStamp')[1] == "null") ||
            //    ($.ti.cookie.getCookie('ItineraryPlannerTimeStamp')[1] == $.ti.tripData.trip.dataPostTime) ){

				$.ti.cookie.setCookie('ItineraryPlanner', $.ti.tripData.trip.id, 'null');
				$.ti.tripData.trip.dataPostTime = 'null';


$('#plannerPromo1').attr('onclick', "retInspireClicked=inspireClicked; inspireClicked=true; return !retInspireClicked;");

				// Set the link value of any promos requiring trip data for query string
				$('#plannerPromo1').attr('href', '/us/ireland-places-to-go/trip/listings/');
//				$('#plannerPromo2').attr('href', '/us/ireland-places-to-go/trip/listings/recommendations/?recid=' + $.ti.tripData.trip.id);
				$('#plannerPromo2').attr('href', '/us/ireland-things-to-see-and-do/whats-on/');

				// Check for reviewer status and handle buttons and events accordingly
				$.ti.reviewer.init();

				// Handle other initialisations
				$.ti.login.init();
				// Initialise share overlay
				$.ti.share.init();
				// Initialise Enquire overlay
				$.ti.enquire.init();
				// Check the autoshow status & add the event for it
				$.ti.panelContent.showOnAdd();

				// Empty the bag in case this isn't the first trip
				$.ti.bag.reset();

				// Add our activities to the bag
				if($.ti.tripData.trip.selectedCategory === 'all') {
					$.ti.bag.fill();
				} else {
					//$.ti.bag.fill('all');
                    $.ti.bag.fill($.ti.tripData.trip.selectedCategory);
				}

				$.ti.panel.setUpPromo();
				//remove any existing activity instances from the calendar
				$('.dayGridActivity').remove();
				$.ti.createTripCalendar.populateCalendar();
				$.ti.panelContent.setShareCommentsOverview();
				$.ti.panelContent.setTripName();
				$.ti.trips.change();
				// Get categories available within the bag

				$.ti.categories.get();
				// IF trip has no activities and user has no other trips then initialise the introduction panel
				if(!$.ti.tripData.trip.tripActivities && !$.ti.tripData.trip.myTrips) {
                    $.ti.nag.init();
                } else {
					$.ti.nag.nag = false;
				}

				// Set trip date
				$.ti.pickDates.showDates();

			//}
			//else{
			//	$.ti.panel.getTripData();
			//}

		}
		else{
			$.ti.panel.getTripData();
		}
    },

	setUpPromo: function() {
        var strings = {
            title: '',
            description: '',
            src: '/shared/resource/images/itinerary_planner/us/buttons/add-to-trip.png'
        };

        // Check for reviewer status and update image accordingly.
        if($.ti.tripData.trip.role == "R") {
            strings.src = "/shared/resource/images/itinerary_planner/us/buttons/unavailable/add-to-trip.png";
        }

        // Check how many we have left and gets some more if needed n.b. causes a trip save
        if($.ti.panel.promos.promo.length <= 0){
            this.getNewPromos();
        } else {
            // get & remove last item from new promo object
            var promo = $.ti.panel.promos.promo.pop();



            if(promo.actEndDate){
            	var endDateArray = promo.actEndDate.split('-');
     			var endDateFormatted = $.datepicker.formatDate('d M yy', new Date(endDateArray[0], endDateArray[1] - 1, endDateArray[2]));
        	}

            // build the html with that object
            var html =  $([ '<div id="panelPromo" class="promo">',
                            '<h3><a href="#">' + promo.actName + '</a></h3>',
                            '<p>' + $.ti.utils.truncate(promo.actDescription, 45) + '</p>',
                            '<p class="smallPrint">' + promo.actCity + '</p>',
                            '<p class="smallPrint">Valid until:' + endDateFormatted + '</p>',
                            '<input id="addPanelPromo" type="image" src="' + strings.src + '" width="102" height="22" ',
//                            'onclick="dcsMultiTrack(\'DCS.dcsuri\', \''+  $.ti.makeSafeOnclickStr(window.location.pathname) +'add_planner_promo\', \'WT.ti\', \''+ $.ti.makeSafeOnclickStr(promo.actName) + ' - Planner Promo Add\')" ',
                            '/>',
                        '</div>'
                    ].join(''));
            // Clear any existing promos
            if($('#panelPromo').length > 0) {
               $('#panelPromo').remove();
            }

            $('#bagContainer').append(html);
            // Attach Promo data to the html object
            $('#panelPromo').data('data', promo);

            $('#panelPromo a').bind('click', function(){
                $.ti.bag.showDetails($(this).closest('div'));
				return false;
            });
        }
	},

    getNewPromos: function() {
        $.ti.ajax.postData('/us/trip/?tripId=' + $.ti.tripData.trip.id, $.ti.tripData, $.ti.panel.saveTripAndPromos, $.ti.panel.setUpPromo);
    },

    saveTripAndPromos: function(data, callback) {

        if(data) {
            $.ti.tripData = data;
            // Seperate promo items from main trip object into own promo object
            if($.ti.tripData.trip.tripPromos) {
                $.ti.panel.promos = $.ti.tripData.trip.tripPromos;
                delete($.ti.tripData.trip.tripPromos);

            }

            callback();
        } else {
            // Throw error - no data present
            // ToDo - How do we present this to the user?

			$.ti.console.log('Error: no trip data returned !!!!!!!!');

			setTimeout(function(){
				plannerCalls++;
				if(plannerCalls < 3) {
					$.ti.panel.getTripData();
				}
			}, 500);

		}
    }



};


})(jQuery);
