var reqHistory;
var SavetoDB = 0;
var domainroot = 'http://'+document.domain+'/';
var ajaxs = Array();
var ajaxshref = Array();
var ajaxsspec = Array();
var ajaxstext = Array();
var currentIndex = -1;
var dirtyTempindex = -1;  

function getDBPages(){
    var myRequest = new Request({
                method: 'get', 
                url: 'dev/getfromdbhistroy.php' , 
                evalScripts : true,
                link :'chain'//,
                //onComplete: function(){
                    //starthistory();
                    //}
                });
    
    myRequest.send();
}


//function starthistory(){
    window.addEvent('domready', function(){
    HistoryManager.initialize();    
    
reqHistory = HistoryManager.register(
        '',
        [0], // default, page 0
        function(values) {
            ajaxUpdate(values[0]);
        },
        function(values) {
            return values[0];
        },
        /(\S+)/ // the regexp to match "everything/fsdfsdf"
    );
    
    getHrefs();
    HistoryManager.start();
    }); // dom ready
//}; 
/* ]]> */


/**
     * Loads the url (by index) if the index is valid and not the current page
     */
function ajaxUpdate(index) {
    if(index == undefined || index == "undefined" ) return;
    if(currentIndex != -1 && index == 0){ 
       index = "newsearch"; 
    }
    if(index != 0){
        if(isDirtyChecker()){  
            var addition = "";
            var oldindex = index; 
            var tempindex;
            
            if(typeof(index) != "number" && index.indexOf('/') != -1){
                tempindex = index.split('/');
                index = tempindex[0];
                addition = tempindex[1];
                }
            var url = getLinkDetailsMaster(index,addition,1) || null;
            if (!url) return;
            
            currentlinkspec = getLinkDetailsMaster(index);
            // fancy state change with classes
            if (currentIndex != -1) {
                linkspec = getLinkDetailsMaster(currentIndex);
                oldhref = currentlinkspec[0].replace(/http.*(\.com|\/kr|:1000|localhost|dev.kr|.uk)\/?/,"");
                updatealllinks(oldhref, 0)
            }
            
            var newhref = currentlinkspec[0].replace(/http.*(\.com|\/kr|:1000|localhost|dev.kr|.uk)\/?/,"");
            updatealllinks(newhref, 1);
            
            if(SavetoDB == 1){
               // SavePageToDB(newhref,index);
            }
            
            // load the new page
            eval(url);
            currentIndex = index;
        
            // updating the history
            reqHistory.setValue(0, oldindex);
        }else{
            dirtyTempindex =  index; 
        }
    }
};




function getHrefs(){

  var pagelinks = $$('.autobutton');
  pagelinks.each(function(el) {
      if(el != null){
          var elhref = el.href;//.replace(domainroot,"");
            
            // save to db
            if(SavetoDB == 1){
                elhref = elhref.replace(/http.*(\.com|\/kr|:1000|localhost|dev.kr|.uk)\/?/,"");   
                if(!urlarray.contains(elhref)){
                    if(elhref.indexOf('#') == -1){
                        key = el.get('text');
                        if(key == ''){key = el.getFirst('img').get('alt')}
                        SavePageToDB(elhref,el.rev+"~"+key)
                    }
                }        
            }
            
            dealwithURL(elhref,el);
            
      }
  });
}

function dealwithURL(elhref,el){
    var urlkey;
    var urlkeyid;
    var addition;
    var Refid = "";
    var Category = '';
    var SearchText = '';
    var JobType = '';
    var Location = '';
    var History = '';
    var Detected = 0;
    var addition = "";
    
     //elhref = elhref.replace(domainroot,"");
     elhref = elhref.replace(/http.*(\.com|\/kr|:1000|localhost|dev.kr|.uk)\/?/,"");     
            
    if(elhref.indexOf('#') == -1){
        if(elhref.indexOf('RemoveJC') != -1){
            Refid = GetsubStringExclusive(elhref, 'VacRef=', '&');
            //http://localhost/kr/run.php?command=ApplyJC&VacRef=3890
            urlkeyid = 'notinterested';
            Detected = 1;
            addition = "/" + Refid;
        }
        
        if(elhref.indexOf('ApplyJC') != -1){
            Refid = GetsubStringExclusive(elhref, 'VacRef=', '&');
            urlkeyid = 'apply';
            Detected = 1;
            addition = "/" + Refid;
        }
    
        if(elhref.indexOf('ShowJobDetails') != -1){
            Refid = GetsubStringExclusive(elhref, 'VacRef=', '&');
            urlkeyid = 'jobdetails';
            Detected = 1;
            addition = "/" + Refid;
        }
        if(elhref.indexOf('RemoveBigJC') != -1){
            Refid = GetsubStringExclusive(elhref, 'VacRef=', '&');
            urlkeyid = 'remove';
            Detected = 1;
            addition = "/" + Refid;
        }
        if(elhref.indexOf('newsDetail') != -1){
            Refid = GetsubStringExclusive(elhref, 'newsID=');
            urlkeyid = 'newsdetail';
            Detected = 1;
            addition = "/" + Refid;
        }
        
        if(elhref.indexOf('jobSearch') != -1){
            Category = GetsubStringExclusive(elhref, 'Category=', '&');
            SearchText = GetsubStringExclusive(elhref, 'SearchText=', '&');
            JobType = GetsubStringExclusive(elhref, 'JobType=', '&');
            Location = GetsubStringExclusive(elhref, 'Location=', '&');
            History = GetsubStringExclusive(elhref, 'History=', '&');
            urlkeyid = 'search';
            Detected = 1;
            addition = "/" + 'Category='+Category+'&SearchText='+SearchText+'&JobType='+JobType+'&Location='+Location+'&History='+History;
        }
        
        if(Detected == 0){
            urlkey = urlarray.indexOf(elhref);
            urlkeyid = urlkeyarray[urlkey];    
        }
        

        //el.set('id', urlkey);
        el.set('href', '#'+urlkeyid+addition+'');
        el.removeEvents();
        el.addEvent('click', function(e) {  
            if (e) new Event(e).stop();
            ajaxUpdate(urlkeyid+addition);    
        });
    }
}
////-------------------------old
  
//function getLinkDetails(elid, mode){
//  //mode 
//  //0 = pull from dom element
//  //1 = pull from ajaxsspec array
//  if(mode == undefined){
//     mode = 0; 
//    }
//  //mode 0 pull from a tag
//    if(mode = 0){  
//      el = $("link"+elid);
//      linkurl = el.get('href');
//      linkspec = el.get('rev');
//      linkspec = linkspec.split("~");
//      //linkspec(0) = ajax function to use
//      //             0 = none
//      //             1 = smartAjax
//      //             2 = Ajax
//      //             3 = simplyAJAX
//      //linkspec(1) = target for the ajax eg "divLeft"
//      //linkspec(2) = optional moo effect to use
//    }else{
//         //mode 1 pull from array bulit with getHrefs
//        linkurl = ajaxshref[elid];
//        linkspec = ajaxsspec[elid];
//        linkspec = linkspec.split("~");
//    }
//      
//      LinkCode = "";
//      
//      switch(linkspec[0]){
//          case '0':
//              LinkCode = "window.location = '"+linkurl+"';";
//              break;
//          case '1':
//              //smartAJAX(sURL, mooEffect)
//              LinkCode = "smartAJAX('"+linkurl+"',"+ linkspec[2] +");";
//              break;
//          case '2':
//              //AJAX(sURL, sDivToSet, mooEffect
//              
//              LinkCode = "AJAX('"+linkurl+"','"+ linkspec[1] +"',"+ linkspec[2] +");";
//              break;
//          case '3':
//              //simplyAJAX(sURL)
//              LinkCode = "simplyAJAX('"+linkurl+"');";
//              break;
//      }
//      return LinkCode;
//  }
 //}
 
 /////////////////////---------------------old end
 
 
 function getLinkDetailsMaster(key,addition,mode){
    if(mode == undefined){
         mode = 0;
    }
    if(addition == undefined){
         addition = "";
    }
  if(key != -1){

        linkspec = fullurlarray[key];
        //linkspec(0) = url
        //linkspec(1) = ajax function to use
      //             0 = none
      //             1 = smartAjax
      //             2 = Ajax
      //             3 = simplyAJAX
      //linkspec(2) = target for the ajax eg "divLeft"
      //linkspec(3) = optional moo effect to use
        //linkspec(4) = the result of the switch below
      linkspec = linkspec.split("~");
      
      LinkCode = "";
      
      switch(linkspec[1]){
          case '0':
              LinkCode = "window.location = '"+linkspec[0]+addition+"';";
              break;
          case '1':
              //smartAJAX(sURL, mooEffect)
              LinkCode = "smartAJAX('"+linkspec[0]+addition+"',"+ linkspec[3] +");";
              break;
          case '2':
              //AJAX(sURL, sDivToSet, mooEffect
              
              LinkCode = "AJAX('"+linkspec[0]+addition+"','"+ linkspec[2] +"',"+ linkspec[3] +");";
              break;
          case '3':
              //simplyAJAX(sURL)
              LinkCode = "simplyAJAX('"+linkspec[0]+addition+"');";
              break;
      }
        linkspec.push(LinkCode);
        if(mode == 0){
            return linkspec;
        }else{
            return linkspec[4];    
        }
    }
    return false;
}


function updatealllinks(url, showhide){
    var currenturl = $$('a[href='+domainroot+url+']');
    
    currenturl.each(function(el) {
        if(showhide == 1 ){
            $(el).addClass('current');
        }else{
            $(el).removeClass('current');    
        }
      });
} 
function getLinkSpec(index){
        var linkspec = "";
        if(isNaN(index)){
            if(index.indexOf('#') == -1 && index.indexOf('~') == -1 && isNaN(index)){
                //#news
                linkspec = fullurlarray[index] + "~" +index;
            }
            if(index.indexOf('~') != -1){
                //1~divLeft~3 etc
                linkspec = index;
            }
        }
        if(!isNaN(index)){
            // number ie 2
            // ti be phased out
            linkspec = ajaxsspec[index];
        }
        
        return linkspec;
}

function SavePageToDB(newhref,index){    
        var linkspec = getLinkSpec(index);

        linkspec = linkspec.split("~");
                //linkspec(0) = ajax function to use
                //             0 = none
                //             1 = smartAjax
                //             2 = Ajax
                //             3 = simplyAJAX
                //linkspec(1) = target for the ajax eg "divLeft"
                //linkspec(2) = optional moo effect to use    
                //linkspec(3) = text key eg #news (no #)
        var myRequest = new Request({method: 'get', url: 'dev/addtodbhistroy.php'});
        var newhref = newhref.replace(/&/g,'~%~');
        myRequest.send('Key='+ linkspec[3].replace(/ /g,'') +'&Url='+newhref+'&MooEffect='+linkspec[2]+'&DivID='+linkspec[1]+'&LoadType='+linkspec[0]+'');
        getDBPages()
}
function GetsubStringExclusive(string, start, end){
    var tempstart = string.indexOf(start);
    tempstart = tempstart + start.length;
    if(end != undefined){
        var tempend = string.indexOf(end, tempstart);
        var resultstring = string.substring(tempstart,tempend);
    }else{
        var resultstring = string.substring(tempstart);
    }
    
    return resultstring;
}