/* Mootools dependancies  XHR, AJAX, JSON */

var XHR=new Class({Implements:[Chain,Events,Options],options:{method:"post",async:true,data:null,urlEncoded:true,encoding:"utf-8",autoCancel:false,headers:{},isSuccess:null},setTransport:function(){this.transport=(window.XMLHttpRequest)?new XMLHttpRequest():(Client.Engine.ie?new ActiveXObject("Microsoft.XMLHTTP"):false)},initialize:function(){var B=Array.associate(arguments,{"url":"string","options":"object"});
this.url=B.url;this.setTransport();this.setOptions(B.options);this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.headers=$merge(this.options.headers);if(this.options.urlEncoded&&this.options.method!="get"){var A=(this.options.encoding)?"; charset="+this.options.encoding:"";this.setHeader("Content-type","application/x-www-form-urlencoded"+A)}this.setHeader("X-Requested-With","XMLHttpRequest")
},onStateChange:function(){if(this.transport.readyState!=4||!this.running){return }this.running=false;this.status=0;$try(function(){this.status=this.transport.status},this);if(this.options.isSuccess.call(this,this.status)){this.onSuccess()}else{this.onFailure()}this.transport.onreadystatechange=$empty},isSuccess:function(){return((this.status>=200)&&(this.status<300))},onSuccess:function(){this.response={text:this.transport.responseText,xml:this.transport.responseXML};
this.fireEvent("onSuccess",[this.response.text,this.response.xml]);this.callChain()},onFailure:function(){this.fireEvent("onFailure",this.transport)},setHeader:function(A,B){this.headers[A]=B;return this},getHeader:function(A){return $try(function(B){return this.getResponseHeader(B)},this.transport,A)||null},send:function(A,C){if(this.options.autoCancel){this.cancel()}else{if(this.running){return this
}}this.running=true;C=C||this.options.data;if(C&&this.options.method=="get"){A=A+(A.contains("?")?"&":"?")+C;C=null}this.transport.open(this.options.method.toUpperCase(),A,this.options.async);this.transport.onreadystatechange=this.onStateChange.bind(this);if((this.options.method=="post")&&this.transport.overrideMimeType){this.setHeader("Connection","close")}for(var B in this.headers){try{this.transport.setRequestHeader(B,this.headers[B])
}catch(D){this.fireEvent("onException",[D,B,this.headers[B]])}}this.fireEvent("onRequest");this.transport.send($pick(C,null));if(!this.options.async){this.onStateChange()}return this},request:function(A){return this.send(this.url,A)},cancel:function(){if(!this.running){return this}this.running=false;this.transport.abort();this.transport.onreadystatechange=$empty;this.setTransport();this.fireEvent("onCancel");
return this}});var Ajax=new Class({Extends:XHR,options:{update:null,evalScripts:false,evalResponse:false},initialize:function(B,A){this.parent(B,A);this.addEvent("onSuccess",this.onComplete,true);if(!["post","get"].contains(this.options.method)){this._method="_method="+this.options.method;this.options.method="post"}this.setHeader("Accept","text/javascript, text/html, application/xml, text/xml, */*")
},onComplete:function(){var A;if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){A=this.response.text}else{A=(this.options.evalScripts)?"":null;this.response.text=this.response.text.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,function(){if(A!==null){A+=arguments[1]+"\n"}return""})}if(this.options.update){$(this.options.update).empty().setHTML(this.response.text)
}if(A){(window.execScript)?window.execScript(A):window.setTimeout(A,0)}this.fireEvent("onComplete",[this.response.text,this.response.xml],20)},request:function(A){A=A||this.options.data;switch($type(A)){case"element":A=$(A).toQueryString();break;case"object":A=Object.toQueryString(A)}if(this._method){A=(A)?this._method+"&"+A:this._method}return this.parent(A)}});Object.toQueryString=function(B){var C=[];
for(var A in B){C.push(encodeURIComponent(A)+"="+encodeURIComponent(B[A]))}return C.join("&")};Element.extend({send:function(A){var B=this.$attributes.send;if(!B){B=this.$attributes.send=new Ajax(this.getProperty("action"),{method:this.method||"post",autoCancel:true})}if(A){B.setOptions(A)}return B.request(this)},update:function(B,A){var C=this.$attributes.update;if(!C){C=this.$attributes.update=new Ajax({update:this,method:"get",autoCancel:true})
}if(A){C.setOptions(A)}C.url=B;return C.request()}});var Json={encode:function(B){switch($type(B)){case"string":return"\""+B.replace(/[\x00-\x1f\\"]/g,Json.$replaceChars)+"\"";case"array":return"["+B.map(Json.encode).filter($defined).join(",")+"]";case"object":var A=[];for(var D in B){var C=Json.encode(B[D]);if($defined(C)){A.push(Json.encode(D)+":"+C)}}return"{"+A.join(",")+"}";case"number":case"boolean":return String(B);
case false:return"null"}return null},$specialChars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r","\"":"\\\"","\\":"\\\\"},$replaceChars:function(A){return Json.$specialChars[A]||"\\u00"+Math.floor(A.charCodeAt()/16).toString(16)+(A.charCodeAt()%16).toString(16)},decode:function(string,secure){if($type(string)!="string"||!string.length){return null}if(secure&&!(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""))){return null
}return eval("("+string+")")}}

/* END Mootools dependancies */

var currentGuideItem;
function updateGuideSegment(segName, item) {
  if(segName) {
    var thisSelect = $("guide-"+segName);
    var selectedRegion = thisSelect.value;
    if(!this.options) {
      that = "regions";
    } else {
      that = getPreviousSeg(segName)+"_"+this.options.selectedRegion;
    }

    if(thisSelect) {
      var aROpts = {
        onComplete: setGuideURL, 
        selectedRegion: selectedRegion,
        method: "get"
      };
      var aR = new Ajax("http://www.smh.com.au/travel/jupiter/destinationlist/"+that+".json", aROpts);
      aR.request();
    }
    
    if(typeof(item) != "undefined" || thisSelect.selectedIndex > -1 && thisSelect.value != 0) {
      var nextType = getNextRegionType(segName);
      if(segName == "region") {
        // Update desc field
        var descField;
        if(descField = $("guide-list")) {
          var aDOpts = {
            onComplete: updateGuideDescBox, 
            onFailure: catchError,
            segName: segName,
            method: "get"
          };
          var listItem = thisSelect.value;
          var value = thisSelect.options[thisSelect.selectedIndex].text;
          var sR = $('selectedRegion');
          sR.empty().innerHTML = value;
          clearNextSiblings(thisSelect);
          var aD = new Ajax("http://www.smh.com.au/travel/jupiter/destinationlist/list_"+listItem+".html", aDOpts);
          aD.request();
        }
      }
      if(nextType) {
        if(typeof(item) == "undefined") {
          item = thisSelect.options[thisSelect.selectedIndex].value;
        }
        var aOpts = {
          onComplete: updateGuideSelectBox,
          onFailure: catchError,
          nextType: nextType,
          segName: segName,
          selectedRegion: selectedRegion,
          method: "get"
        };
        var a = new Ajax("http://www.smh.com.au/travel/jupiter/destinationlist/"+segName+"_"+item+".json", aOpts);
        a.request();
      }
    }
  }
}

function setGuideURL(resp) {
  if($('guideForm')) {
    if(resultObj = Json.decode(resp)) {
      for(var a = 0; a < resultObj.length; a++) {
        if(resultObj[a].id == this.options.selectedRegion) {
          if(resultObj[a].url) {
            $('guideForm').setAttribute("action", resultObj[a].url);
          }
        }
      }
    }
  }
}

function getGuideURL() {
  if($('guideForm')) {
    window.location = $('guideForm').action;
  }
}

function catchError(resp) {
  clearNextSiblings("guide-"+this.options.segName);
}

function updateGuideSelectBox(resp) {
  if(resp) {
    var holder = $('guide-region-holder');
    var resultObj;
    if(resultObj = Json.decode(resp)) {
      if(resultObj.length == 2 && this.options.nextType == "country") {
         removeNextSiblings($("guide-"+this.options.segName));
         if(!window.ie) {
           var hiddenInput = new Element("input");
           var props = {
            "name": "country",
            "value": resultObj[1].id,
            "type": "hidden",
            "id": "guide-"+this.options.nextType
           };
           hiddenInput.setProperties(props);
           hiddenInput.inject(holder);
         }
         updateGuideSegment("country", resultObj[1].id);
      } else if(resultObj.length > 2) {
        var currentEle;
        if(currentEle = $('guide-'+this.options.segName)) {
          removeNextSiblings($('guide-'+this.options.segName));
        }
        var selectEle;
        selectEle = new Element("select");
        selectEle.id = "guide-"+this.options.nextType;
        selectEle.addEvent("change", updateGuideSegment.bind(this, this.options.nextType));
        var selectLabel = new Element("label");
        selectLabel.innerHTML = "Select "+this.options.nextType;
        selectLabel.id = "guide-"+this.options.nextType+"-label";
        selectLabel.setAttribute("for", "guide-"+this.options.nextType);
         for(var a = 0; a < resultObj.length; a++) {
          var thisOpt = resultObj[a];
          if(typeof(thisOpt) != "undefined") {
            if(thisOpt.id && thisOpt.name) {
              var opt = new Element("option");
              opt.value = thisOpt.id;
              opt.empty().innerHTML = thisOpt.name;
              opt.injectInside(selectEle);
            }
          }
        }
        selectLabel.inject(holder);
        selectEle.inject(holder);
      } else {
        removeNextSiblings($("guide-"+this.options.segName));
      }
    }
  }
}

function updateGuideDescBox(resp) {
  if(resp) {
    var guide;
    if(guide = $('guide-list')) {
      guide.empty().innerHTML = resp;
    }
  }
}

function getListItemName() {
  var regionS;
  var thing = "";

  if(regionS = $("guide-region")) {
    if(regionS.value != 0) {
      thing += regionS.value;
    }

    return thing;
  }
}

function getNextRegionType(type) {
  if(type == "region") {
    return "country";
  } else if(type == "country") {
    return "city";
  } 
  return false;
}

function getPreviousSeg(type) {
  if(type == "city") {
    return "country";
  } else if(type == "country") {
    return "region";
  } 
  return false;
}

function clearNextSiblings(thisSibling) {
  thisSibling = $(thisSibling);
  var next = thisSibling;
  while(next = next.getNext()) {
    if(next != thisSibling) {
      if(next.getTag() == "select" || next.getTag() == "input") {
        next.empty();
      }
    }
  }
}

function removeNextSiblings(thisSibling) {
  var childrenEles = $("guide-region-holder").getChildren();
  var rem = false;
  childrenEles.each(function(thisChild) {
    if(rem) {
      var p = document.getElementById("guide-region-holder");
      if(thisChild.id != thisSibling.id && thisChild.id+"-label" != thisSibling.id) {
        var c = document.getElementById(thisChild.id);
        if(c.nodeName.toLowerCase() == "select") {
          p.removeChild(c);      
        } else {
          $(c).remove();
        }
      }
    }
    if(thisChild == thisSibling) {
      rem = true;
    }
  });
}

