ccs.tripPlanner = {}; // package declaration
ccs.tripPlanner.path = '/ccs/modletInclude/tripplanner/';
ccs.tripPlanner.FLY_IMAGE_ID = 'flyPin';
var TP_WINDOW_STATE = "tp_windowstate";
ccs.tripPlanner.Main = function() {
   var newSrc = ""; //variable to store the new src for the iframe that gets loaded bya  timer to get around an IE bug
   var mousePos;
   var tripplannerMaximised;
   var self;

    // constructor function
   function constructorFn() {
      self = this;
      registerOnLoad(self.init);
   }

    // init function called once document is loaded
   constructorFn.prototype.init = function() {
   }


   constructorFn.prototype.updatedCoord = function (keyId, posX, posY) {
      //need to update the relevant td cell with
      $("tdsib_" + keyId).style.background = "#26ff02";
   }


   constructorFn.prototype.addPinImage = function () {
      //<img style="position:absolute;top:500px;left:208px;z-index:1000;display:none" src="" border="0" id="flag1">
      var imgElement = document.createElement("IMG");
      imgElement.id = ccs.tripPlanner.FLY_IMAGE_ID;
      imgElement.style.position = "absolute";
      imgElement.style.top = "0px";
      imgElement.style.left = "0px";
      imgElement.style.zIndex = 1000;
      imgElement.style.display = "none";
      imgElement.src = ccs.contextPath + "/applications/" + ccs.appName + "/templates/images/tripplanner/flag.png";
      document.body.insertBefore(imgElement, document.body.firstChild);
   }

   constructorFn.prototype.loadIframe = function(act) {
      if (act == "save") {
         self.setIFrameLarge();
         document.saveFrm.saved_data.value = self.getSaveJson();
         document.saveFrm.selected_themes.value = self.getSavedThemes();

         document.saveFrm.submit();
      } else {
         if (act == "ask_an_expert") {
            self.newSrc = "tripplanner-ask-an-expert";
         } else if (act == "register") {
            self.newSrc = "tripplanner-register";
         } else if (act == "login") {
            self.newSrc = "tripplanner-login";
         } else if (act == "send_to_an_agent") {
            self.newSrc = "tripplanner-getaquote";
         } else {
            self.newSrc = "tripplanner-iframe?tripplanner_req=" + act.toLowerCase();
         }
         self.setIFrameLarge();
         setTimeout(self.loadIFrameSrc, 200);
      }
      document.getElementById("innerFrame").style.visibility = "visible";
      return "";
   }

   constructorFn.prototype.setIFrameLarge = function() {
      var yInside = 0;
      if ($("inside_container")) {
         yInside = parseInt($("inside_container").cumulativeOffset().left);
      }
      var iy = $("divTripplannerMax").cumulativeOffset().top ;
      var ix = $("divTripplannerMax").cumulativeOffset().left - yInside ;

      var swfInternalSetLeft = 235 ;
      var swfInternalSetTop = 76 ;

      document.getElementById("innerFrame").style.top = swfInternalSetTop + iy + "px";
      document.getElementById("innerFrame").style.left = swfInternalSetLeft + ix + "px";
      document.getElementById("innerFrame").style.width = "432px";
      document.getElementById("innerFrame").style.height = "222px";
   }
   constructorFn.prototype.loadIFrameSrc = function() {
      document.getElementById("innerFrame").src = self.newSrc;
   }
   constructorFn.prototype.closeIframe = function() {
      document.getElementById("innerFrame").src = "tripplanner-iframe?tripplanner_req=frame_blank";
      document.getElementById("innerFrame").style.visibility = "hidden";
   }
   constructorFn.prototype.confirmCloseIframe = function () {
      self.closeIframe();
      return true;
   }


   constructorFn.prototype.viewArticleDetail = function (id, newwin) {
      if (newwin) {
         window.open(ccs.contextPath + "/content/en/za/page904?oid=" + id + "&sn=Detail#detail")         
      } else {
         location.href = ccs.contextPath + "/content/en/za/page904?oid=" + id + "&sn=Detail#detail"
      }
   }

   constructorFn.prototype.iframeLoginCallback = function (hasSavedData) {
      var flashObject = self.getMovie("Main");
      if (flashObject != null) {
         flashObject.js_loggedIn(hasSavedData);
      } else {
         alert("mmm, can't find the tripplanner on the page");
      }
   }

   constructorFn.prototype.iframeCloseInFlash = function () {
      var flashObject = self.getMovie("Main");
      if (flashObject != null) {
         flashObject.js_closePopup();
      } else {
         alert("mmm, can't find the tripplanner on the page");
      }
   }

   //3 states
   // minimised - the tripplanner minimised bar loads
   // maximised - the tripplanner loads in a maximised state
   // maximised_intro - the intro shell loads which in turn loads the tripplanner
   constructorFn.prototype.showState = function (state) {
      if (state == null || state == "" || state == "maximised") {
         self.tripplannerMaximised = true;
         if ($("divTripplannerMax").style.display != "block") {
            self.showMaximised();
         }
         setCookie(TP_WINDOW_STATE, state);
      } else if (state == "maximised_intro") {
            self.tripplannerMaximised = true;
            if ($("divTripplannerMax").style.display != "block") {
               self.showMaximisedIntro();
            }
            setCookie(TP_WINDOW_STATE, "maximised");
      } else {
         self.tripplannerMaximised = false;
         $("divTripplannerMax").style.display = "none";
         ccs.tripPlanner.navBar.show();
         setCookie(TP_WINDOW_STATE, state);
      }
   }

   constructorFn.prototype.showMaximised = function () {
      setCookie(TP_WINDOW_STATE, "maximised");
      $("divTripplannerMin").style.display = "none";
      //Effect.SlideDown($("divTripplannerMax"), { duration: 3.0 });
      if ($("divTripplannerMaxContent").innerHTML.length == 0) {
         $("divTripplannerMaxContent").innerHTML = maximisedLoad;
      }
      $("divTripplannerMax").style.display = "block";
      self.tripplannerMaximised = true;
   }

   constructorFn.prototype.showMaximisedIntro = function () {
      setCookie(TP_WINDOW_STATE, "maximised");
      $("divTripplannerMin").style.display = "none";
      //Effect.SlideDown($("divTripplannerMax"), { duration: 3.0 });
      if ($("divTripplannerMaxContent").innerHTML.length == 0) {
         $("divTripplannerMaxContent").innerHTML = homePageMasterLoad;
      }
      $("divTripplannerMax").style.display = "block";
      self.tripplannerMaximised = true;
   }

   constructorFn.prototype.iframeSendTofriendCallback = function () {
      self.loadIframe("send_to_friend");
   }

   constructorFn.prototype.iframeSendToAgentCallback = function () {
      self.loadIframe("send_to_an_agent");
   }


   constructorFn.prototype.getWishlist = function () {
      var flashObject = self.getMovie("Main");
      if (flashObject != null) {
         return flashObject.js_getWishList();
      } else {
         alert("mmm, can't find the tripplanner on the page");
         return "";
      }
   }


   constructorFn.prototype.printWishlist = function () {
      //popup a window which will the parent fir its data
      //popup("tripplanner-iframe?tripplanner_req=print");
		 lrgWindow=window.open("tripplanner-iframe?tripplanner_req=print","pic","scrollbars=yes,menubar=no,width=500,height=550,resizable=yes");  
		 lrgWindow.print();
   }


   constructorFn.prototype.getSaveJson = function () {
      var flashObject = self.getMovie("Main");
      if (flashObject != null) {
         return flashObject.js_getSaveJson();
      } else {
         alert("mmm, can't find the tripplanner on the page");
         return "";
      }
   }
   //extract themes from the json object savedData that we get from the tripplanner
   constructorFn.prototype.getSavedThemes = function () {
      var savedData = self.getSaveJson();
      var obj = savedData.evalJSON();
      //extract the themes from the json
      var themes = obj.interfaceState.themeItemValues;
      var strThemes = "";
      for (t in themes) {
         strThemes += (strThemes.length > 0 ? "," : "") + t + "=" + themes[t];
      }
      return strThemes;

   }



   constructorFn.prototype.onClickRegister = function () {
      //we need to tell the flash app that we clicked register
      var flashObject = self.getMovie("Main");
      if (flashObject != null) {
         flashObject.js_regsiterOnClick();
      } else {
         alert("mmm, can't find the tripplanner on the page");
      }

   }


   constructorFn.prototype.getMovie = function (movieName) {
      //try both for different browsers
      var obj = window[movieName];
      if (obj == null) obj = window.document[movieName];
      return obj;
   }


   constructorFn.prototype.pinToMap = function (articleId, containerDiv) {
      var wishListMousePos = null;


      if (self.tripplannerMaximised) {
         var iy = $("divTripplannerMax").cumulativeOffset().top + flashMVHeight - 23;
         var ix = $("divTripplannerMax").cumulativeOffset().left + (flashMVWidth / 2) - 70;
         wishListMousePos =  {x:ix, y:iy};
      } else {
         var iy = $("minFlag").cumulativeOffset().top;
         var ix = $("minFlag").cumulativeOffset().left;
         wishListMousePos =  {x:ix, y:iy};
      }

      var par = new Parallel();
      $(containerDiv).style.visibility = "hidden";
      $(containerDiv).style.display = "none";
      
      $(ccs.tripPlanner.FLY_IMAGE_ID).style.left = (self.mousePos.x - 10) + "px";

      ymouse = (self.mousePos.y - 10);

      //now for a ridiculous IE hack!
      var isIE = navigator.appName.indexOf("Microsoft") != - 1;
      if (isIE) {
         ymouse = ymouse + document.viewport.getScrollOffsets().top;
      }

      $(ccs.tripPlanner.FLY_IMAGE_ID).style.top = ymouse + "px";

      var t1 = new Tween($(ccs.tripPlanner.FLY_IMAGE_ID).style, 'left', Tween.regularEaseIn, parseInt($(ccs.tripPlanner.FLY_IMAGE_ID).style.left), wishListMousePos.x, 1, 'px');
      var t2 = new Tween($(ccs.tripPlanner.FLY_IMAGE_ID).style, 'top', Tween.regularEaseIn, parseInt($(ccs.tripPlanner.FLY_IMAGE_ID).style.top), wishListMousePos.y, 1, 'px');

      par.addChild(t1);
      par.addChild(t2);

      t1.onMotionFinished = function() {
         self.pinMotionEnd(articleId, true);
      };

      $(ccs.tripPlanner.FLY_IMAGE_ID).style.display = "block";
      $(ccs.tripPlanner.FLY_IMAGE_ID).style.visibility = "visible";
      par.start();

   }

   constructorFn.prototype.mouseMove = function(ev){
      ev           = ev || window.event;
      self.mousePos = self.mouseCoords(ev);

   }

   constructorFn.prototype.mouseCoords = function (ev){
      if (ev.pageX || ev.pageY) {
         return {x:ev.pageX, y:ev.pageY};
      }
      return {
         x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
         y:ev.clientY + document.body.scrollTop - document.body.clientTop
      };
   }

   constructorFn.prototype.pinpoint = function (keyId, keyName, posX, posY) {
      var mvName = "Main";

      var flashObject = self.getMovie(mvName);
      if (flashObject != null) {
         flashObject.js_pinPoint(keyId, keyName, posX, posY);
      } else {
         alert("mmm, can't find the tripplanner on the page");
      }
   }
   constructorFn.prototype.pinMotionEnd = function (articleId, livePin) {
      var mvName = "Main";
      if (self.tripplannerMaximised) {
         $(ccs.tripPlanner.FLY_IMAGE_ID).style.display = 'none';
         var flashObject = self.getMovie(mvName);
         if (flashObject != null) {
            flashObject.js_pinToMap(articleId);
         } else {
            alert("mmm, can't find the tripplanner on the page");
         }
      } else {
         $(ccs.tripPlanner.FLY_IMAGE_ID).style.display = 'none';
         ccs.tripPlanner.navBar.addToWishlist(articleId);
      }
   }


   constructorFn.prototype.startUp = function (pageName) {
      if (maximisedLoadNeedFlash.length > 0) {
         //user has no flash...or not right version....
         //so we rather show the big maximised state by default so that the window
         //is at least big enough for him to see whats going on
         $("divTripplannerMax").style.display = "block";
         $("divTripplannerMax").innerHTML = maximisedLoadNeedFlash;
         $("divNeedFlash").style.display = "block";

      } else {
         //load minimised in its hidden div... the minismised swf will determine what to actually show
         //by calling ccs.tripplanner.main.showState
         //$("divTripplannerMin").style.display = "block";
         /**
         *  Open Rules:
         *  New Session
         *     If we are on the homen page we will open full tripplanner by default
         *     If not, we open minimised view by default
         *  Existing Session
         *     We check the session cookie "tp_windowstate" to decide
         */

         var cookieEnabled=(navigator.cookieEnabled)? true : false;

         //if navigator,cookieEnabled is not supported
         if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){
             document.cookie="testcookie";
             cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false;
         }

         if (!cookieEnabled) {
            $("divTripplannerMin").innerHTML = "You do not have cookie enabled, this prevents the trip planner from functioning correctly."
            $("divTripplannerMin").style.display = "block";
         } else {
            var tripState = getCookie(TP_WINDOW_STATE);
            var stateStr = null;
            if (tripState != null && tripState.length != 0) {
               //new session ...base it on home page
               stateStr = tripState;

            } else { 
	            //changed to ALWAYS open up maximised on first visit regardless of which page it is
//               if (pageName != "home") {
//                  stateStr = "minimised";                  
//               } else {
                  //this IS a new session, i.e tripplanner has not loaded yet else we would not have passed the condition above
                  stateStr = "maximised_intro";
//               }
            }

//            stateStr = "maximised_intro";
            
            self.showState(stateStr);
         }

      }
   }




   return new constructorFn();
}


ccs.tripPlanner.NavBar = function() {
   var self;
   var flagShadowTop; //store initial position of flag
   var flagShadowLeft;
   var flagTop;
   var DEBUG ;
   var getCount;

   var wishlist;    //comma separated list of ids

    // constructor function
   function constructorFn() {
      self = this;
      registerOnLoad(self.init);
      self.getCount = 0;
      wishlist = "";
   }



    // init function called once document is loaded
   constructorFn.prototype.init = function() {
      self.flagShadowTop = parseInt($("minFlagShadow").style.top);
      self.flagShadowLeft = parseInt($("minFlagShadow").style.left);
      self.flagTop = parseInt($("minFlag").style.top);
      self.getWishlistForSession();
   }

   constructorFn.prototype.setDebugMode = function () {
      self.DEBUG = true;
   }

   constructorFn.prototype.show = function () {
      if ($("divTripplannerMin").style.display != "block") {
         $("divTripplannerMin").style.display = "block";
      }
      //read the count from cookie
      self.updateDisplayCount();
   }
   constructorFn.prototype.clearWishlist = function () {
      //setCookie("tp_wishlist", "");
      self.wishlist = "";
   }


   constructorFn.prototype.getWishlistAsList = function () {
      var idList = self.wishlist; //getCookie("tp_wishlist");
      if (idList == null) {
         idList = "";
      }
      if (self.DEBUG) {
         self.getCount ++;
         $("divGetWishlist").value = new Date() + " - " + self.getCount + " :" + idList + "\n" + $("divGetWishlist").value  + "\n";
      }

      return idList;
   }
   constructorFn.prototype.getWishlistAsArray = function () {
      var idList = self.getWishlistAsList();

      var arr = new Array();
      if (idList.length > 0) {
         arr = idList.split(",");
      }
      return arr;
   }

   constructorFn.prototype.updateDisplayCount = function () {
      //read the count from cookie
      $("minWishlistCount").innerHTML =  self.getWishlistAsArray().length + "";
   }
   constructorFn.prototype.inWishlist = function (articleId) {
      //read the count from cookie
      var arr =  self.getWishlistAsArray();
      var ret = false;
      for (i = 0; i < arr.length; i++) {
         if (arr[i] == articleId) {
            ret = true;
            break;
         }
      }
      return ret;
   }
   //will append diff to wishlist
   constructorFn.prototype.setWishlist = function (list) {
      if (list.length > 0) {
         if (self.DEBUG) {
            $("divSetWishlist").value = new Date() + ":" + list + "\n" + $("divSetWishlist").value + "\n";
         }



         //var arr = list.split(",");
         //for (i = 0; i < arr.length; i++) {
         //   self.addToWishlistNoAnim(arr[i])
         //}
         self.saveWishlist(list);
         self.updateDisplayCount();
      }
   }

   //will append diff to wishlist
   constructorFn.prototype.removeFromWishlist = function (articleId) {
      var arr =  self.getWishlistAsArray();
      var newlist = "";
      for (i = 0; i < arr.length; i++) {
         if (arr[i] != articleId) {
            newlist += (newlist.length > 0 ? "," : "") +  arr[i];
         }
      }
      self.saveWishlist(newlist);
   }

   constructorFn.prototype.saveWishlist = function (list) {
      //setCookie("tp_wishlist", list);
      self.wishlist = list;

      self.saveForSession();
   }

   //We need store the updated wishlist string in the session for the minismised view
   //so that the tripplanner, or navbar can pick it up on the next page.
   //this is opposed to using cookies which we had so many problems with in firefow
   constructorFn.prototype.saveForSession = function () {
      if (self.wishlist) {
         new Ajax.Request(
               ccs.contextPath + '/json/' + ccs.appName + '/en/modules/tripplanner/set_session_wishlist.json?wl=' + escape(self.wishlist), {
            onSuccess: function(reply) {

               //don't need top do anything
            }
         }
         )
      }
   }

   constructorFn.prototype.getWishlistForSession = function () {
      if (!ccs.tripPlanner.main.tripplannerMaximised) {
         new Ajax.Request(
               ccs.contextPath + '/json/' + ccs.appName + '/en/modules/tripplanner/get_session_wishlist.json', {
            onSuccess: function(reply) {
               try {
                  var retVal = reply.responseText.evalJSON();
                  if (!retVal.error) {
                     self.wishlist = retVal.wishlist;
                     self.updateDisplayCount();
                  }
               } catch (e) {
                  //failure so we simpoy set it to zero
                  self.wishlist = "";
               }

            }
         }
         )
      }
   }

   constructorFn.prototype.addToWishlist = function (articleId) {
      self.animateFlag();
      self.addToWishlistNoAnim(articleId);

   }
   constructorFn.prototype.addToWishlistNoAnim = function (articleId) {
      if (!self.inWishlist(articleId)) {
         var list =  self.getWishlistAsList();
         list += (list.length > 0 ? "," : "") + articleId;
         self.saveWishlist(list);
      }
      self.updateDisplayCount();
   }
   constructorFn.prototype.maximise = function () {
      ccs.tripPlanner.main.showMaximised();
   }
   constructorFn.prototype.animateFlag = function () {
      var howHigh = 30;
      var seq = new Sequence();


      var flagWidth = parseInt($("minFlag").style.width);
      var flagHeight = parseInt($("minFlag").style.height);

      var duration = 0.5;

      var t1 = new Tween($("minFlagShadow").style, 'top', Tween.regularEaseOut, self.flagShadowTop,  self.flagShadowTop - howHigh, duration, 'px');
      var t2 = new Tween($("minFlagShadow").style, 'left', Tween.regularEaseOut, self.flagShadowLeft,  self.flagShadowLeft - howHigh, duration, 'px');
      var t3 = new Tween($("minFlag").style, 'top', Tween.regularEaseOut, self.flagTop, self.flagTop - howHigh, duration, 'px');

      var par = new Parallel();
      par.addChild(t1);
      par.addChild(t2);
      par.addChild(t3);

      var t1Reverse = new Tween($("minFlagShadow").style, 'top', Tween.regularEaseIn, self.flagShadowTop- howHigh,  self.flagShadowTop , duration, 'px');
      var t2Reverse = new Tween($("minFlagShadow").style, 'left', Tween.regularEaseIn,self.flagShadowLeft - howHigh,  self.flagShadowLeft , duration, 'px');
      var t3Reverse = new Tween($("minFlag").style, 'top', Tween.regularEaseIn, self.flagShadowTop - howHigh, self.flagTop, duration, 'px');

      var parReverse = new Parallel();
      parReverse.addChild(t1Reverse);
      parReverse.addChild(t2Reverse);
      parReverse.addChild(t3Reverse);

      seq.addChild(par);
      seq.addChild(parReverse);
//      seq.onMotionFinished = function() {
//         self.animateFlag();
//      };

      seq.start();
   }


   return new constructorFn();
}


function debug(obj) {
   var x = 'Dump of ' + obj + '\r\n';
   for (i in obj) {
      x += i + ' = ' + obj[i] + '\r\n';
   }

   prompt('Object dump - copy & paste into text editor', x);
}



ccs.tripPlanner.main = new ccs.tripPlanner.Main();
ccs.tripPlanner.navBar = new ccs.tripPlanner.NavBar();
document.onmousemove = ccs.tripPlanner.main.mouseMove;
ccs.tripPlanner.main.addPinImage();

