
var timer = {
          time: 0,
          now: function(){
                    return (new Date()).getTime();
          },
          start: function(){
                    this.time = this.now();
          },
          since: function(){
                    return this.now()-this.time;
          }
}

function onVoteDone(){

          var send_div = document.getElementById('send_div');
          if(send_div != null){

                    send_div.innerHTML = "<p class='vote_button'>thanks</p>";
          }
}

function onVote(){

          var good_btn = document.getElementById('good');
          if(good_btn != null){

                    var good = 1;

                    if(! good_btn.checked){

                              good = 0;
                    }

                    var url = "/vote/" + good_btn.value + "/" + good;
                    sendAjax(url, onVoteDone);
          }
}



var curentPart = "";
var vgt = null;
var recentHash = "";
var useAjax = !isWindowExplorer();
useAjax = false;
var horScrollerWidth = -1;
var printNotes = true;
var printTabs = true;

window.onresize = function(){

          centralizeSearchBox();
          setSizes();
          
          var url = window.location.href;
          if(url.indexOf('/song/') != -1){
                    if(useAjax){

                              var startIndex = url.indexOf("#") + 1;
                              url = '/ajax' + url.substring(startIndex);

                    } else {

                              var lastIndex = url.lastIndexOf('/');
                              url = url.substring(0, lastIndex);
                    }

                    requestSong(url);
          } 
}

function getMainWidth(){

          //var main = document.getElementById('main');
          var winWidth = getWinWidth();
          var left_panel = document.getElementById('left_panel');
          var ad = document.getElementById('ad');

          if(horScrollerWidth == -1){
                    horScrollerWidth = getScrollerWidth();
          }

          return (winWidth - left_panel.offsetWidth - ad.offsetWidth - horScrollerWidth);
}

function getMainHeight(){

          var winHeight = getWinHeight();
          var top_panel = document.getElementById('top_panel');
          var topHeight = 65;
          if(top_panel != null){

                    topHeight = top_panel.offsetHeight;
          }

          return (winHeight - topHeight);
}


function adjustControlPanel(elementid){

          var el = document.getElementById(elementid);
          if(el.clientHeight < el.scrollHeight){

                    if(horScrollerWidth == -1){
                              horScrollerWidth = getScrollerWidth();
                    }

                    var width = "" + (150 + horScrollerWidth) + "px";
                    el.style.width = width;
                    
          } else {

                    el.style.width = "150px";
          }
}

function centralizeSearchBox(){

          if(isOpera()){
                    
                    var search_box_panel = document.getElementById("search_box_panel");
                    if(search_box_panel != null){
                              search_box_panel.style='text-align:left';
                              var pos = "" + (getWinWidth() / 2) - (search_box_panel.offsetWidth / 2) + "px";
                              search_box_panel.style.left = pos;
                    }
          }
}

function setSizes(){

          var top_panel= document.getElementById("top_panel");
          if(top_panel != null){

                    var win_height = getWinHeight();
                    var height = win_height - top_panel.offsetHeight;

                    setElementHeight('right_panel', height);
                    setElementHeight('ad', height);
                    setElementHeight('main', height);
                    setElementHeight('left_panel', height);

                    adjustControlPanel('left_panel');
          }
          
}

function setVGTDocSize(){

          var top_panel= document.getElementById("top_panel");
          var vgtDoc =  document.getElementById("VGTDoc");
          if(top_panel != null && vgtDoc != null){
                    
                    vgtDoc.style.overflowX='hidden';

                    var song_title = document.getElementById("song_title");
                    if(song_title != null){
                              var win_height = getWinHeight();
                              vgtDoc.style.height = (win_height - song_title.offsetHeight - top_panel.offsetHeight) + "px";
                    }
          }
}



function toggleDataDisplayed(type, button_id){

          var el = document.getElementById(button_id);
          if(el != null){

                    if(el.className != "disabled"){

                              if(el.className == 'pushed'){

                                        
                                        el.className = 'enabled';
                                        vgt.showDives(type, false);
                                        return false;
                              } else {

                                        
                                        el.className = 'pushed';
                                        vgt.showDives(type, true);
                                        return true;
                              }
                    }
          }

          return true;
}

function toggleChords(){

          toggleDataDisplayed("chords", "toggle_chords");
}

function toggleLyrics(){

          toggleDataDisplayed("lyrics", "toggle_lyrics");
}

function toggleNotes(){

          printNotes = toggleDataDisplayed("notes", "toggle_notes");
}

function toggleTab(){

          printTabs = toggleDataDisplayed("tab", "toggle_tab");
}

function toggleGuitarNeck(){

          toggleDataDisplayed("guitarNeck", "toggle_guitar_neck");
}

var PART_STATE_INACTIVE = 0;
var PART_STATE_ACTIVE = 1;
var PART_STATE_PREGRESS = 2;

function setPartState(part_id, state){

          var el = document.getElementById(part_id);
          if(el != null){

                    switch(state){

                              case PART_STATE_INACTIVE:
                                        el.className = "enabled";
                                        break;

                              case PART_STATE_ACTIVE:
                                        el.className = "pushed";
                                        document.body.style.cursor = "auto";
                                        break;

                              case PART_STATE_PREGRESS:
                                        el.className = "progress";
                                        document.body.style.cursor = "wait";
                                        break;
                    }
          }
}

function setDisplayState(element_id, divType){

          var divVisible = vgt.getDivVisible(divType);
          var chordsExists = vgt.isExists(divType);

          vgt.showDives(divType, divVisible && chordsExists);

          var el = document.getElementById(element_id);
          if(el != null){

                    if(!divVisible && chordsExists){

                              el.className = 'enabled';

                    } else if(divVisible && chordsExists ) {

                              el.className = 'pushed';
                    } else {

                              el.className = 'disabled';
                    }
          }
}

function drawPartFinishedCallback(){

          setPartState(curentPart, PART_STATE_ACTIVE);
          
//      setDisplayState('toggle_chords', 'chords');
//      setDisplayState('toggle_lyrics', 'lyrics');
}

function changePart(part_id){

          if(part_id != curentPart && !vgt.isBusy()){

                    var part_data = document.getElementById(part_id + "_data");
                    if(part_data != null){

                              setPartState(part_id, PART_STATE_PREGRESS);
                              setPartState(curentPart, PART_STATE_INACTIVE);

                              curentPart = part_id;

                              var base64String = part_data.innerHTML;
                              var buffer = decode_Base64(base64String);
                              vgt.parseAsync(buffer, drawPartFinishedCallback);
                    }
          }
}

function load_notes(){

          var buffer;
          var vgtDoc = document.getElementById("VGTDoc");
          if(vgtDoc != null){

                    curentPart = "";

                    var div = document.getElementById("lyrics_data");

                    vgt = new VGTDraw(vgtDoc, div.innerHTML);

                    div = document.getElementById("chordsDefinition");
                    buffer = decode_Base64(div.innerHTML);
                    vgt.parse(buffer);

                    div = document.getElementById("text");
                    if(div !=  null){
                              buffer = decode_Base64(div.innerHTML);
                              vgt.parse(buffer);
                    }


                    changePart("0");

                    setVGTDocSize();
                    
                    return true;
          }

          return false;
}


function printSong(songId, songName){

          if(curentPart== ""){
                    alert("No part is selected");
                    return;
          }

          var url = "/print_song/" + songId + "/" + curentPart + "?printNotes=" + printNotes + "&printTabs=" + printTabs;
          
          window.open(url, "print_song",  "menubar=1,scrollbars=1,width=800,addressbar=1");
}

function editSongLyrics(songId, clientWidth){

          var url = "/edit_lyrics/" + songId + "/" + clientWidth;

          window.location.href = url;
}

function findChildById(node,  requiredId){

          var children = node.childNodes;
          for(var i = 0; i < children.length; i++)
          {
                    if(children.item(i).id == requiredId)
                    {
                              return children.item(i);
                    }
          }

          return null;
}


function handleResponseContainer(container){

          var main = document.getElementById('main');

          var control_panel = document.getElementById('control_panel');
          if(control_panel!= null){

                    var inner_html_control_panel = findChildById(container, 'inner_html_control_panel');
                    if(inner_html_control_panel != null){

                              control_panel.innerHTML = inner_html_control_panel.innerHTML;
                              inner_html_control_panel.innerHTML = "";
                    } else {

                              control_panel.innerHTML = "";
                    }
          }

          var notes = findChildById(container, 'notes');
          if(notes != null){
                    nowDisplayingSong = true;
                    main.innerHTML = notes.innerHTML;
                    load_notes();
                    setSizes();
          }

          main.scrollTop=0;

          var search_results = findChildById(container, 'search_results');
          if(search_results != null){

                    main.innerHTML = search_results.innerHTML;
                    setSizes();
          }

          var title = findChildById(container, 'title');
          if(title != null){

                    document.title = title.innerHTML;
          }
}

function searchResultsCallback(){

          var htm = getResponse();
          var container = document.createElement('div');
          container.innerHTML = htm;
          handleResponseContainer(container);
}

function onSearch(){

          var search = document.getElementById('search_box');
          var query = search.value;

          query = query.replace(/^\s+|\s+$/g, '') ;

          if(query.length > 0){
                    requestSearch(query, 0);
          }
}

function setLocationHash(url){

          var hash = url;
          var ajax = '/ajax';
          if(hash.indexOf(ajax) != -1){

                    hash = hash.substring(Number(ajax.length));
          }

          window.location.hash = hash;
          recentHash = hash;
}

function loadDataToMainDiv(url){

          if(useAjax){

                    if(url.substring(0,1) =="#"){
                              url = url.substring(1);
                    }

                    setLocationHash(url);

                    url = url.replace(/ /g, "%20");
                    sendAjax(url, searchResultsCallback);

          }  else {

                    if(url.indexOf("/artist/") != -1 || url.indexOf("/search/") != -1){

                              url += "/" + getMainHeight();
                    }

                    window.location.href = url;
          }
}

function  sendAjax(url, callbackFunc){

          if(url.indexOf("/ajax/song/") != -1){

                    var div = document.getElementById('main');
                    url += "/" + div.offsetWidth;
          }

          execAjax(url, callbackFunc);
}

function requestSong(url){

          if(useAjax){
                    if(url.substring(0,1) =="#"){
                              url = url.substring(1);
                    }

                    setLocationHash(url);

                    url = url.replace(/ /g, "%20");
                    sendAjax(url, searchResultsCallback);

          } else {

                    //                    url += "/" + (div.offsetWidth);
                    url += "/" + getMainWidth();
                    window.location.href = url;
          }
}

function requestSearch(query, offset){

          var height = getMainHeight();

          if(useAjax){

                    var request = "/ajax/search/" + query + "/" + offset + "/" + height;
                    setLocationHash(request);
                    request = request.replace(/ /g, "%20");
                    sendAjax(request, searchResultsCallback);

          } else {
                    /*
                                         var array = document.location.href.split("/search/");
                                        url = array[0] + "/search/" + query + "/" + offset + "/" + mainHeight;
                                        document.location = url;

 */
                    var url = "/search/" + query + "/" + offset + "/" + height;
                    window.location.href = url;
          }
}

function requestArtist(artistId, artistName, offset){

          var height = getMainHeight();

          if(useAjax){

                    var request = "/ajax/artist/" + artistId + "/" + offset +  "/" + height;
                    setLocationHash(request);
                    request = request.replace(/ /g, "%20");
                    sendAjax(request, searchResultsCallback);

          } else {

                    /*
                                         var array = document.location.href.split("/artist/");
                                        url = array[0] + "/artist/" + name + "/" + id + "/" + offset + "/" + mainHeight;
                                        document.location = url;

 */
                    var url = "/artist/" + artistName + "/" + artistId + "/" + offset + "/" + height;
                    window.location.href = url;
          }
}

function requestArtistsIteration(letter, offset){

          var height = getMainHeight();

          var url = "/iterate_artists/" + offset + "/" + height;
          if(letter != ""){
                              
                    url +=  "?letter=" + letter;
          }
          window.location.href = url;
}
/*
function requestArtistsIteration(offset){

          var height = getMainHeight();

          if(useAjax){

                    var request = "/ajax/iterate_artists/" + offset +  "/" + height;
                    setLocationHash(request);
                    request = request.replace(/ /g, "%20");
                    sendAjax(request, searchResultsCallback);

          } else {

                    var url = "/iterate_artists/" + offset + "/" + height;
                    window.location.href = url;
          }
}
*/

function initFromAjax(){
          
          var url = window.location.hash;
          if(url.indexOf('#') != -1){
                    url  =url.substring(1);
                    url = "/ajax" + url;
                    url = url.replace(/ /g, "%20");
                    sendAjax(url, searchResultsCallback);

                    return true;
          }

          return false;
}


function historyPoll(){

          var hash = window.location.hash.substring(1);
          if(recentHash != hash){
                    recentHash = "/ajax" + hash;

                    loadDataToMainDiv(recentHash);
          }
}

function initHistoryHadler(){

          recentHash = window.location.hash;
          setInterval(historyPoll, 500);
}

function correctWidthInURL(){

          if(!useAjax){

                    var url = window.location.href;

                    if(url.indexOf("/song/") != -1){

                              var tmp = getFieldByIndex(url, 6, -1);
                              var mainWidth = getMainWidth();
                              
                              if(tmp == -1){
                                        // there is no width in the url
                                        window.location.href = url + "/" + mainWidth;
                              }  else if(tmp != mainWidth){

                                        var index = url.lastIndexOf("/");
                                        url = url.substring(0, index);
                                        url += "/" + mainWidth;
                                        window.location.href = url;
                                        return true;
                              }
                    }
          }

          return false;
}


function correctHeightInURL(){

          var mainHeight = getMainHeight();
          var tmp;
          var id;
          var offset;

          if(useAjax){

                    var hash  = window.location.hash;

                    if(hash.indexOf("/artist/") != -1){

                              tmp = getFieldByIndex(hash, 4, 0);
                              if(tmp != mainHeight){

                                        id = getFieldByIndex(hash, 2, 0);
                                        offset = getFieldByIndex(hash, 3, 0);
                                        requestArtist(id, "name",  offset);
                                        return true;
                              }
                              
                    } else if (hash.indexOf("/search/") != -1){

                              tmp = getFieldByIndex(hash, 4, 0);
                              if(tmp != mainHeight){

                                        var query = getFieldByIndex(url, 2);
                                        offset = getFieldByIndex(url, 3, 0);
                                        requestSearch(query, offset);
                                        return true;
                              }
                    } else if (hash.indexOf("/iterate_artists/") != -1){

                              tmp = getFieldByIndex(hash, 3, 0);
                              if(tmp != mainHeight){

                                        offset = getFieldByIndex(url, 3, 0);
                                        requestArtistsIteration(offset);
                                        return true;
                              }
                    }

          } else {

                    var url = window.location.href;

                    if(url.indexOf("/artist/") != -1){

                              tmp = getFieldByIndex(url, 7, 0);
                              if(tmp != mainHeight){

                                        var name = getFieldByIndex(url, 4, "name");
                                        id = getFieldByIndex(url, 5, 0);
                                        offset = getFieldByIndex(url,6, 0);

                                        requestArtist(id, name,  offset);

                                        return true;
                              }
                    } else if(url.indexOf("/search/") != -1){

                              tmp = getFieldByIndex(url, 6, 0);
                              if(tmp != mainHeight){

                                        query = getFieldByIndex(url, 4, "");
                                        offset = getFieldByIndex(url, 5, 0);

                                        requestSearch(query, offset);

                                        return true;
                              }
                    }
          }

          return false;
}


function getFieldByIndex(url, index, defaultValue){

          var i;
          var c = 0;
          var ret;

          for(i=0; i < index && c != -1; i++){

                    c = url.indexOf("/", c+1);
          }

          if(c == -1){
                    return defaultValue;
          }

          i = c + 1;
          c = url.indexOf("/", i);
          if(c == -1){
                    ret = url.substring(i);
                    if(ret == ""){
                              ret = defaultValue;
                    }
                    return ret;
          }

          ret = url.substring(i, c);
          if(ret == ""){
                    ret = defaultValue;
          }
          return ret;
}

function correctAjaxOperation(){

          var url = window.location.href;
          var ajaxIndex = url.indexOf("/#/") ;
          var array;
          var id;
          var query;
          var offset;
          var height = getMainHeight();


          if(useAjax && ajaxIndex == -1){

                    if(url.indexOf("/song/") != -1){

                              id = getFieldByIndex(url, 5, 0);

                              array = document.location.href.split("/song/");
                              url = array[0] + "/#/song/" + id;
                              document.location = url;

                              return true;
                    } else if (url.indexOf("/artist/") != -1){

                              id = getFieldByIndex(url, 5, 0);
                              offset = getFieldByIndex(url, 6, 0);
                              array = document.location.href.split("/artist/");
                              url = array[0] + "/#/artist/" + id + "/" + offset + "/" + height;
                              document.location = url;
                              return true;
                    } else if (url.indexOf("/search/") != -1){

                              query = getFieldByIndex(url, 4, "");
                              offset = getFieldByIndex(url, 5, 0);
                              array = document.location.href.split("/search/");
                              url =  array[0] + "/#/search/" + query + "/" + offset + "/" + height;
                              document.location = url;
                              return true;
                    } else if (url.indexOf("/iterate_artists/") != -1){

                              offset = getFieldByIndex(url, 4, 0);
                              array = document.location.href.split("/iterate_artists/");
                              url =  array[0] + "/#/iterate_artists/" + offset + "/" + height;
                              document.location = url;
                              return true;
                    }
                    
          } else if(!useAjax && ajaxIndex != -1){

                    var mainWidth = getMainWidth();
                    var hash = window.location.hash;

                    if(hash.indexOf("/#/song/") != -1){

                              id = getFieldByIndex(url, 5, 0);

                              array = document.location.href.split("/#/song/");
                              url = array[0] + "/song/name/" + id + "/" + mainWidth;
                              document.location = url;

                              return true;
                    } else if (hash.indexOf("/#/artist/") != -1){

                              id = getFieldByIndex(hash, 5, 0);
                              offset = getFieldByIndex(hash, 6, 0);

                              url = document.location + "/artist/name/" + id + "/" + height;
                              document.location = url;

                              return true;
                    } else if (hash.indexOf("/#/search/") != -1){

                              query = getFieldByIndex(url, 5, 0);
                              offset = getFieldByIndex(url, 6, 0);

                              array = document.location.href.split("/#/search/");
                              url = array[0] + "/search/" + query + "/" + offset + "/" + height;
                              document.location = url;

                              return true;
                    }

                    return true;
          }

          return false;
}

function init(){

          var handled = false;

          handled = correctAjaxOperation();
          if(handled){
                    return;
          }

          setSizes();
          centralizeSearchBox();

          handled = correctHeightInURL();
          if(handled){
                    return;
          }

          handled = correctWidthInURL();
          if(handled){
                    return;
          }

          var needClientWidth = document.getElementById('need_client_width')
          if(needClientWidth !=  null){

                    var div = document.getElementById('main');
                    window.location.href += "/" + (div.offsetWidth);
          }

          /*
          if(useAjax && !handled){

                    handled = initFromAjax();
          }
*/
          if(!handled) {

                    var container = document.getElementById('response_container')
                    if(container !=  null){
                              handleResponseContainer(container);
                    }
          }

          initHistoryHadler();
}

function onHomePage(){

          if(useAjax){
                    loadDataToMainDiv("");

          }  else {

                    window.location.href = "/";
          }
}

function onLearnTabsClick(){

          loadDataToMainDiv("/ajax/learntabs");
}

function onSearchBoxFocus(){

          var search = document.getElementById('search_box');
          search.select();
}

function onSearchBoxKey(event){

          var evt = event || window.event;
          var keyCode = evt.which || evt.keyCode;

          if(keyCode == 13){
                    onSearch();
          }
}

function openContactUs(){

          window.open('/contact_us', 'contact_us',  'menubar=0,scrollbars=1,width=560,height=420,addressbar=0');
}
