// actually id is 'menu'
function Menu(id){

    this.element = $(id);

    this.isShown = false;
    this.id = id;

    this.toggle = function() {
        if(this.isShown) {
            this.hide();
        } else {
            this.show();
        }
    }

    this.show = function(){
        if(this.isShown) {
          return;
        }
        this.element.show();
        this.isShown = true;
    }

    this.hide = function(){
        if(!this.isShown) {
          return;
        }
        this.element.hide();
        this.isShown = false;
    }
}

function wt4over(event) {
    try{wt4duk.show();}catch(e){};
}

function elementHasAncestor(element, ancestor) {
    while (element && element.id != ancestor) {
        element = element.parentNode;
    }
    return !!element;
}

function wt4out(event) {
    if (!elementHasAncestor(event.relatedTarget, "logoCont")) {
        try{wt4duk.hide();}catch(e){};
    }
}

//-------------------------------------------------------------


var radio, wt4duk, userFormManager, animUtil, anyTextLayout, wd, creepy;

function initCreepy() {

  if(typeof(creepyDatas) == 'undefined' || creepyDatas == null) {
    alert("no creepyDatas");
    return;
  }

  var creepyDatasHash = $H(creepyDatas);
  //alert(creepyDatas.toJSON);

  creepyDatasHash.each(function(pair) {

    var creepyKey = pair.key;
    var creepyData = pair.value;
    var creepy = createCreepy(creepyData);

    var targetElement = $(creepyKey);

    if(targetElement) {

      processCreepyTargetElement(targetElement, creepy);
    } else {

      var targetElements = $$("*." + creepyKey);

      if(targetElements.length == 0) {
        //alert("target element " + creepyKey + " not found, ignoring");
      } else {
        for(var i = 0; i < targetElements.length; i++) {

          var targetElement = targetElements[i];
          processCreepyTargetElement(targetElement, creepy);

        }
      }
    }
  });
}

function processCreepyTargetElement(targetElement, creepy) {

  var boxes = targetElement.select("*.box");

  //alert("Found " + boxes.length + " creeby boxes for " + creepyKey);
  boxes.each(function(box) {

    creepy.process(box);

    if(box.show) {
      box.show();
    } else {
      box.style.display = "block";
    }

    var errorCount = creepy.getErrorsCount();
    if(errorCount > 0) {
        alert(errorCount + " errors occurred while processing creepy");
    }
  });

  targetElement.show();
}

function createCreepy(creepyData) {

    if(creepyData == null ){
      throw new Error("Creepy styles hash must not be null");
    }

    var splittingStrategy = SplittingStrategy.newStrategy(creepyData.strategy.value);
    var textAlign = creepyData.textAlign.value;

    var creepy = new Creepy(splittingStrategy, textAlign);

    for(propName in creepyData) {

        var prop = creepyData[propName];
        var type = prop.type;
        var value = prop.value;
        var policy;
        var splittingStrategy;

        if(type == "values") {
          policy = new CreepyValuesRef(propName, value);
        } else if (type == "range") {
          policy = new CreepyRange(propName, value);
        } else {
            //strategy and suchlike
            continue;
        }

        creepy.addPolicy(policy);

    }

    return creepy;
}

function initRadioMenu() {
  radio = new Menu("radio");
}

function initLogoMenu() {
  wt4duk = new Menu("wt4duk");
  $('logoCont').observe('mouseover', wt4over);
  $('logoCont').observe('mouseout', wt4out);
}

function initMenu() {
    initRadioMenu();
    initLogoMenu();
}

function init(suppressLogo, suppressPositioning) {

  var animateLogo = !suppressLogo;

  animUtil = new AnimationUtil(configuration);
  animUtil.init(animateLogo);
  wd = animUtil.getWindowDimensions();

  initMenu();

  var state = loggedIn ? new LoggedIn() : new NotLoggedIn();
  director = new UserFormManager(state);

  var content = $('content');
  if(content) {
     var positioner = suppressPositioning ? new QuietPositioner() : new CirclePositioner();
     initTextLayout(content, positioner);
  }

  var theHole = $('theHole');
  if(theHole) {
     initTheCenter(theHole)
  }

  initCreepy();

}

function initTextLayout(parentElement, positioner) {

  anyTextLayout  = new AnyTextLayout('page', new TextItemCreationStrategy(), positioner);

  var components = parentElement.childElements();
  for(var i = 0; i < components.length; i++){
  	anyTextLayout.addElement(components[i]);
  }

  wd.addListener(anyTextLayout);

  anyTextLayout.startJoinAnim(animUtil);
  anyTextLayout.setPositions(wd);
  anyTextLayout.showAll();

}

function initTheCenter(theHole) {

  var holeItem = new ItemBuilder().newItem(theHole);

  wd.addListener({
  	windowChanged: function(windowDimensions){
  	  var holeCenter = windowDimensions.getCenterPoint().newPoint(0, 50);
      var holeHalfHeight = Math.round(theHole.getHeight() / 2);
      //alert("half height: " + holeHalfHeight + ", center : " + holeCenter.getY());
      if(holeCenter.getY() < holeHalfHeight + 70) {
        holeCenter.setY(holeHalfHeight + 70);
      }
      holeItem.setPosition(holeCenter);
  	}
  });

  var holeCenter = wd.getCenterPoint().newPoint(0, 50);
  var holeHalfHeight = Math.round(theHole.getHeight() / 2);
  //alert("half height: " + holeHalfHeight + ", center : " + holeCenter.getY());
  if(holeCenter.getY() < holeHalfHeight + 70) {
    holeCenter.setY(holeHalfHeight + 70);
  }
  holeItem.setPosition(holeCenter);
  holeItem.show();

}

function tweakPwd(element) {
  if(element.type != "password") {
     try {
       element.type = "password";
     } catch(e) {
       //
     }
  }
}

//-------------------------------------------------------------

var LoggedInState = Class.create();

LoggedInState.prototype = {

  initialize: function() {
    this.formManager = null;
  },

  setFormManager : function(formManager) {
    this.formManager = formManager;
  }
}

//-------------------------------------------------------------

var LoggedIn = Class.create();

LoggedIn.prototype = {

  assignElements : function() {
    // return quetly;
  },

  authClicked : function() {
      return;
  }

}

Object.extend(LoggedIn.prototype, LoggedInState.prototype);

//-------------------------------------------------------------

var NotLoggedIn = Class.create();

NotLoggedIn.prototype = {

  assignElements : function() {
    this.formManager.assignElement("loginForm");
    this.formManager.assignElement("registration");
    this.formManager.assignElement("loginMessage");
    this.formManager.assignElement("regMessage");
    this.formManager.assignElement("userFormBlock");
    this.formManager.assignElement("regFormBlock");
    this.formManager.assignElement("regFormTable");
    this.formManager.assignElement("authHeader");
  },

  authClicked : function() {
      this.formManager.userFormBlock.toggle();
      this.formManager.regFormBlock.toggle();
      var formShown = this.formManager.userFormBlock.style.display == "block";
      //this.formManager.authHeader.style.borderBottom = formShown ? 2px solid #fc9128
  },

  regClicked : function() {
      this.formManager.regFormTable.toggle();
  }

}

Object.extend(NotLoggedIn.prototype, LoggedInState.prototype);

//-------------------------------------------------------------

var ErrorState = Class.create();

ErrorState.prototype = {

  authClicked : function() {
      alert("Error initializing Form Director, check your code");
  },

  regClicked : function() {
      alert("Error initializing Form Director, check your code");
  }

}

Object.extend(ErrorState.prototype, LoggedInState.prototype);

//-------------------------------------------------------------

var UserFormManager = Class.create();

UserFormManager.prototype = {

  initialize: function(state) {

    this.valid = true;

    this.state = state;
    this.state.setFormManager(this);
    this.state.assignElements();

    if(!this.valid) {
      this.state = new ErrorState();
      this.state.setFormManager(this);
    }

  },

  authClicked : function() {
      this.state.authClicked();
  },

  regClicked : function() {
      this.state.regClicked();
  },

  uploadMyStuffClicked : function() {
      this.state.uploadMyStuffClicked();
  },

  assignElement : function(elementName) {
    var element = $(elementName)
    if(element == null) {
      alert("Element " + elementName + " not found, check your code");
      this.valid = false;
    }
    this[elementName] = element;

    if(element && element.toggle == null) {
       element.toggle = function() {
         this.style.display = this.style.display == "none" ? "block" : "none";
       }
    }

  },

  evaluateResponse : function(transport, messageContainer, userName) {

    var messages = eval("(" + transport.responseText + ")");

    if(messages == null || messages.length == 0) {

      location.reload();
      return;

      this.state = new LoggedIn();
      this.state.setFormManager(this);


      var replacement = '<div class="header">'
                      + '<a style="text-align:left" class="box" href="/4duk/userHome.action">Привет, '
                      + userName
                      + '<br />&#9658; Моя страница</a><br />'
                      + '<a style="text-align:left;color:red;" class="box" href="/4duk/userLogout.action">'
                      + '&#9650; Выход</a></div>';

      try {
          //alert(this["loginForm"]);
        $($("loginForm").parentNode).update(replacement);
      } catch(e) {
        alert(e);
      }

      var elementsToRemove = $$('*.removeAfterLogin');

      elementsToRemove.each(
        function(element) {
          //alert(element.id);
          element.remove();
        }
      );

      var elementsToDisplay = $$('*.displayAfterLogin');
      elementsToDisplay.each(
        function(element) {
          //alert(element.id);
          element.show();
        }
      );

      var comments = $("comments");
      if(comments) {
        comments.show();
        $("doodadBottom").scrollIntoView();
      }

    } else if(messages.length == 1) {
        messageContainer.show();
        messageContainer.innerHTML = messages[0];
    } else {
      messageContainer.show();
      messageContainer.innerHTML = "<ul><li>" + messages.join("</li><li>") + "</li></ul>";
    }
  },

  doLogin: function () {

    this.loginMessage.innerHTML = "";
    this.loginMessage.hide();
    new Ajax.Request('/4duk/userLogin.action', {
      method: 'post',
      postBody: Form.serialize(this.loginForm),
      onComplete: function(transport) {
        //alert(transport.responseText);
        this.evaluateResponse(transport, this.loginMessage, this.loginForm.elements["user.name"].value);
      }.bind(this)
    });
  },

  doRegistration: function () {

    this.regMessage.innerHTML = "";
    this.regMessage.hide();
    new Ajax.Request('/4duk/userRegistration.action', {
      method: 'post',
      postBody: Form.serialize(this.registration),
      onComplete: function(transport) {
        //alert(transport.responseText);
        this.evaluateResponse(transport, this.regMessage, this.registration.elements["user.name"].value);
      }.bind(this)
    });
  }
}

var WhatIsPlaying = Class.create();

WhatIsPlaying.MILLLIS_UNTIL_NEXT_REQUEST_IF_ERROR = 1000;

WhatIsPlaying.prototype = {

  initialize: function(url, theWindow) {

    this.url = url;
    this.theWindow = theWindow;
    var doc = theWindow.document;
    this.artistElement = doc.getElementById('artist');
    this.titleElement = doc.getElementById('title');

    this.wtpDebug = {};
    this.wtpDebug.secondsUntilNextRequest = doc.getElementById('secondsUntilNextRequest');
    this.wtpDebug.minutes = doc.getElementById('minutes');
    this.wtpDebug.seconds = doc.getElementById('seconds');
    this.wtpDebug.duration = doc.getElementById('duration');
    this.wtpDebug.valid = (
      this.wtpDebug.secondsUntilNextRequest != null
      && this.wtpDebug.minutes != null
      && this.wtpDebug.seconds != null
      && this.wtpDebug.duration != null);

    this.artistCreepy = createCreepy(this.theWindow.creepyDatas['artist']);
    this.titleCreepy = createCreepy(this.theWindow.creepyDatas['title']);

    this.artist = "";
    this.title = "";

    this.theWindow.__WhatIsPlaying__ = this;

  },

  toggleCreepy : function() {

    this.artistElement.innerHTML = this.artist;
    this.titleElement.innerHTML = this.title;
    this.artistCreepy.process(this.artistElement);
    this.titleCreepy.process(this.titleElement);
  },

  setNewValues : function(artist, title, millisUntilNextRequest, doSetTimeout) {

    this.artist = artist;
    this.title = title;
    this.millisUntilNextRequest = millisUntilNextRequest;
    this.toggleCreepy();
    if(doSetTimeout) {
      this.theWindow.setTimeout("__WhatIsPlaying__.request()", this.millisUntilNextRequest);
    }
  },

  doDebug : function(response) {

    if(!this.wtpDebug.valid) {

      return;
    }

    var duration = response.duration;
    var minutes = duration.minutes;
    var seconds = duration.seconds;

    this.wtpDebug.secondsUntilNextRequest.innerHTML = Math.ceil(response.millisUntilNextRequest / 1000) + "sec";
    this.wtpDebug.minutes.innerHTML = minutes;
    this.wtpDebug.seconds.innerHTML = seconds;
    this.wtpDebug.duration.innerHTML = request.millisUntilNextRequest;

  },

  request : function() {

    new Ajax.Request(this.url, {
     asynchronous : true,
     onSuccess : function(request) {

         var response = eval("(" + request.responseText + ")");

         this.doDebug(response);
         if(response.error) {
           this.setNewValues("Sбой. Бывает.", "Неизвестно, что играет :-(", WhatIsPlaying.MILLLIS_UNTIL_NEXT_REQUEST_IF_ERROR, false);
         } else {
           this.setNewValues(response.artist, response.title, response.millisUntilNextRequest, true);
         }

       }.bind(this),
     onError : function(request) {
         this.setNewValues("Sбой", "Неизвестно, что играет :-(", WhatIsPlaying.MILLLIS_UNTIL_NEXT_REQUEST_IF_ERROR);
     }
    });

    // this.setNewValues("Sбой. Бывает.", "Неизвестно, что играет :-(", WhatIsPlaying.MILLLIS_UNTIL_NEXT_REQUEST_IF_ERROR, false);
  }
}

function RandomRange(lowerLimit, upperLimit) {
    this.lowerLimit = lowerLimit;
    this.upperLimit = upperLimit;
}

RandomRange.prototype.next = function() {

    var range = this.upperLimit - this.lowerLimit + 1;
    var fraction = Math.floor(range * Math.random());
    return fraction + this.lowerLimit;

}

function toggleUserStuffForm() {
  var userStuffForm  = $('userStuffForm');
  if(userStuffForm) {
    userStuffForm.show();
  } else {
    userFormManager.authClicked();
  }
  //userStuffForm.scrollIntoView();
}

function openVideoGuide() {
  //window.open('/4duk/videoguide.action','videoguide','width=640,height=610');
  alert("Пункт меню уже есть, а контента еще нет. Ну, Вы понимаете.\n\nНаоборот было бы нисколько не лучше, уверяем Вас!\n\nЧерез несколько ночей здесь что-нибудь появится. Просим прощения за за неудобство.");
}


