/*******************************************************************************
 * Model
 */
OMVC.VotingPollModel = function () {
  var that = this;

  /*
   * Observable subjects
   */
  this.modelInitialized     = OMVC.makeObservableSubject();
  this.PollUpdated          = OMVC.makeObservableSubject();
  this.Voted                = OMVC.makeObservableSubject();
  this.EmailError           = OMVC.makeObservableSubject();

  /*
   * Properties
   */
  var uid = 0;                       // Poll id
  var pollDetails = [];              // Poll details
  var anonymous = 0;                 // Anon mode
  var hasVote = 0;                   // AlreadyVoted
  var selected = 0;                  // Selected item

  /*
   * Methods
   */
  // Any initial stuff
  this.initialize = function(category) {
    uid = category;
    hasVote = jQuery.cookie("mwvoteVoice" + uid);
    that.getPollDetails();
    that.modelInitialized.notifyObservers();
  };

  // Get details
  this.getPollDetails = function() {
    jQuery.ajax({
      url: mwvoteAjaxUrl,
      data: {action: 'getPoll', uid: uid},
      dataType: 'json',
      success: function(result) {
        pollDetails = result;
        that.PollUpdated.notifyObservers();
      }
    });
  };

  // Getter
  this.get = function(varName) {
    return eval(varName);
  };

  // Set anonymous mode
  this.setAnonMode = function(anon) {
    anonymous = anon;
  };

  // Set selected item
  this.select = function(id) {
    selected = id;
  };

  // Vote
  that.vote = function(name, email) {
    jQuery.ajax({
      url: mwvoteAjaxUrl,
      data: {action: 'vote', item: pollDetails[selected].uid, name: name, email: email, anonymous: anonymous},
      dataType: 'json',
      success: function(result) {
        if(result.status == 'ok') {
          jQuery.cookie("mwvoteVoice" + uid, 1, {path: '/'});
          that.Voted.notifyObservers();
        } else {
          jQuery.cookie("mwvoteVoice" + uid, 1, {path: '/'});
          that.EmailError.notifyObservers();
        }
      }
    });
  };

};


/*******************************************************************************
 * View
 */
OMVC.VotingPollView = function (model, rootObject) {
  var that = this;
  that.picture = 0;
  
  /*
   * HTML oblects
   */
  that.category = jQuery('<div/>')
      .addClass('category')
      .appendTo(rootObject);
  that.intro = jQuery('<div/>')
      .addClass('intro')
      .html('Sie haben eine Stimme pro Kategorie — setzen Sie diese gut ein!')
      .appendTo(rootObject);
  that.conditions = jQuery('<div/>')
      .addClass('conditions')
      .append(
          jQuery('<a/>')
              .html('Teilnehmebedinungen')
              .attr('href', mwvoteTC))
      .appendTo(rootObject);
  jQuery('<div/>')
      .addClass('clear')
      .appendTo(rootObject);
  that.detailsContainer = jQuery('<div/>')
      .addClass('details-container')
      .appendTo(rootObject);
  that.image = jQuery('<div/>')
      .addClass('image')
      .appendTo(that.detailsContainer);
  that.prev = jQuery('<div/>')
      .addClass('prev')
      .appendTo(that.detailsContainer);
  that.next = jQuery('<div/>')
      .addClass('next')
      .appendTo(that.detailsContainer);
  that.voteBtn = jQuery('<div/>')
      .addClass('vote')
      .appendTo(that.detailsContainer);
  that.images = jQuery('<div/>')
      .addClass('images')
      .appendTo(that.detailsContainer);
  that.pager = jQuery('<div/>')
      .addClass('pager')
      .appendTo(that.detailsContainer);
  that.details = {};
  that.details.company_logo = jQuery('<img/>')
      .appendTo(
          jQuery('<div/>')
              .addClass('company-logo')
              .appendTo(that.detailsContainer)
      );
  that.details.company = jQuery('<div/>')
      .addClass('value')
      .appendTo(
          jQuery('<div/>')
              .addClass('details-item company')
              .append(jQuery('<label/>').html('Bewerber:'))
              .appendTo(that.detailsContainer)
      );
  that.details.land = jQuery('<div/>')
      .addClass('value')
      .appendTo(
          jQuery('<div/>')
              .addClass('details-item land')
              .append(jQuery('<label/>').html('Land:'))
              .appendTo(that.detailsContainer)
      );
  that.details.article_name = jQuery('<div/>')
      .addClass('value')
      .appendTo(
          jQuery('<div/>')
              .addClass('details-item article-name')
              .append(jQuery('<label/>').html('Artikelbezeichung:'))
              .appendTo(that.detailsContainer)
      );
  that.details.article_number = jQuery('<div/>')
      .addClass('value')
      .appendTo(
          jQuery('<div/>')
              .addClass('details-item article-number')
              .append(jQuery('<label/>').html('Artikelnummer:'))
              .appendTo(that.detailsContainer)
      );
  that.details.descriptionContainer = jQuery('<div/>')
      .addClass('details-item description')
      .append(jQuery('<label/>').html('Kurzbeschreibung:'))
      .appendTo(that.detailsContainer)

  that.details.description = jQuery('<div/>')
      .addClass('value')
      .appendTo(that.details.descriptionContainer);
  that.facebook = jQuery('<div/>')
      .addClass('facebook')
      .appendTo(that.details.descriptionContainer);
  that.twitter = jQuery('<div/>')
      .addClass('twitter')
      .html('<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://markeding-award.at/" data-text="Neuheit: Lottery Cup beim marke[ding] Voting: #werbeartikel #award #marketing" data-count="horizontal" data-lang="de">Twittern</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>')
      .appendTo(that.details.descriptionContainer);
  that.google = jQuery('<div/>')
      .addClass('google')
      .html('<g:plusone size="medium" count="true" href="http://markeding-award.at/"></g:plusone>')
      .appendTo(that.details.descriptionContainer);

  that.listContainer = jQuery('<div/>')
      .addClass('list-container')
      .appendTo(rootObject);

  that.blender = jQuery('<div/>')
      .addClass('mwvote-blender')
      .hide()
      .appendTo(jQuery('body'));
  that.popup = jQuery('<div/>')
      .addClass('mwvote-popup')
      .hide()
      .appendTo(jQuery('body'));
  that.popupHeader = jQuery('<div/>')
      .addClass('header')
      .appendTo(that.popup);
  that.nameVote = jQuery('<div/>')
      .addClass('option option1 active')
      .html('Ja, ich will ein iPad2 gewinnen!')
      .append(
          jQuery('<div/>')
              .addClass('comment')
              .html('Dazu benötigen wir allerdings Ihre Kontaktdaten! Wär\' doch schade, wenn das iPad2 jemand anderes bekommt - oder?')
      )
      .appendTo(that.popup);
  that.anonVote = jQuery('<div/>')
      .addClass('option option2')
      .html('Nein, lieber anonym voten')
      .append(
          jQuery('<div/>')
              .addClass('comment')
              .html('Sie können Ihre Stimme für Ihren Favoriten auch gerne anonym abgeben, scheiden aber bei der Verlosung des iPad2 aus.')
      )
      .appendTo(that.popup);
  that.popupVoteBtn = jQuery('<div/>')
      .addClass('vote-btn')
      .appendTo(that.popup);
  that.popupNote = jQuery('<div/>')
      .addClass('note')
      .html('Sie habe nur eine Stimme pro Kategorie<br />Mehrfach Stimmen werden nicht gezählt.')
      .appendTo(that.popup);
  that.popupClose = jQuery('<div/>')
      .addClass('close')
      .html('Fenster schließen')
      .prepend(jQuery('<span/>').html('&times; '))
      .appendTo(that.popup);
  that.form = jQuery('<div/>')
      .addClass('form')
      .appendTo(that.popup);
  that.popupNameLabel = jQuery('<label/>')
      .html('Ihr Name')
      .appendTo(that.form);
  that.popupName = jQuery('<input/>')
      .appendTo(that.form);
  that.popupEmailLabel = jQuery('<label/>')
      .html('Email-Adresse')
      .appendTo(that.form);
  that.popupEmail = jQuery('<input/>')
      .appendTo(that.form);
  that.popupEmailError = jQuery('<div/>')
      .addClass('mwvote-popup')
      .hide()
      .appendTo(jQuery('body'))
      .append(
          jQuery('<div/>')
              .html('Sie haben bereits mit dieser E-Mail-Adresse abgestimmt!')
              .addClass('header')
      );
  that.popupEmailClose = jQuery('<div/>')
      .addClass('close')
      .html('Fenster schließen')
      .prepend(jQuery('<span/>').html('&times; '))
      .appendTo(that.popupEmailError);
  that.popupThanks = jQuery('<div/>')
      .addClass('mwvote-popup')
      .hide()
      .appendTo(jQuery('body'))
      .append(
          jQuery('<div/>')
              .html('Danke für Ihre Stimme und viel Spaß bei marke[ding]!')
              .addClass('header'))
      .append(
          jQuery('<div/>')
              .html('Um Ihre Chancen auf den Gewinn des iPad2 zu erhöhen, melden sie Sich jetzt auch noch zur marke[ding] in Wels oder Wien an und besuchen Sie uns am 6.9.2011 in Wels und/oder 8.9.2011 in Wien. <br /><br />Der Eintritt für Fachbesucher ist kostenlos. <br /><br />> <a href="http://markeding.at/besucher/">jetzt anmelden</a>')
              .addClass('text'));
  that.popupThanksClose = jQuery('<div/>')
      .addClass('close')
      .html('Fenster schließen')
      .prepend(jQuery('<span/>').html('&times; '))
      .appendTo(that.popupThanks);



  // Big item renderer
  that.switchTo = function(id) {
    model.select(id);
    that.picture = 0;
    var details = model.get('pollDetails');
    var item = details[id];
    that.details.company.html(item.company);
    if(that.company_logo == '' || that.company_logo == 'NULL' || that.company_logo == 'null' || that.company_logo == null) {
      that.details.company_logo.hide();
    } else {
      that.details.company_logo.show();
      that.details.company_logo.attr('src', item.company_logo);
    }
    that.details.land.html(item.land);
    that.details.article_name.html(item.article_name);
    that.details.article_number.html(item.article_number);
    that.details.description.html(item.description);
    that.image.css('background-image', 'url(' + item.images[that.picture] + ')');
    that.pager.html((id + 1) + ' von ' + details.length);
    // Highlight icon
    jQuery('.list-container .icon').removeClass('active');
    jQuery('.list-container .icon[rel="'+id+'"]').addClass('active');
    // Prev/next
    that.prev.unbind();
    that.next.unbind();
    var items = details.length;
    var id_prev = (id == 0) ? items - 1 : id - 1;
    var id_next = (id == items - 1) ? 0 : id + 1;
    that.prev.bind('click', function() { that.switchTo(id_prev); });
    that.next.bind('click', function() { that.switchTo(id_next); });
    // that.image.bind('click', that.changeImage);
    // facebook
    that.facebook.html('<fb:like href="' + item.url + '" send="false" layout="button_count" width="96" show_faces="false" font=""></fb:like>');
    FB.XFBML.parse(jQuery(that.facebook).get(0));
    // Images pager
    that.images.html('');
    if(item.images.length > 1) {
      that.images.html('Bilder: ');
      jQuery.each(item.images, function(index) {
        that.images.append(
          jQuery('<span/>')
              .html(index + 1)
              .attr('rel', index)
              .bind('click', function() {
                that.changeImage(parseInt(jQuery(this).attr('rel'), 10));
              })
        );
        if(index < item.images.length - 1) {
          that.images.append(' | ');
        }
      });
    }
    jQuery(that.images).find('[rel="0"]').addClass('active');
    // Add a header to popup
    that.popupHeader.html('Jetzt Ihre Stimme für ' + item.name + ' abgeben!');

  };

  // Change image
  that.changeImage = function(idImage) {
    var details = model.get('pollDetails');
    var id = model.get('selected');
    var item = details[id];
    var images = item.images.length;
    // that.picture = (that.picture == images - 1) ? 0 : (that.picture + 1);
    // that.image.css('background-image', 'url(' + item.images[that.picture] + ')');
    that.image.css('background-image', 'url(' + item.images[idImage] + ')');
    jQuery(that.images).find('span').removeClass('active');
    jQuery(that.images).find('[rel="'+idImage+'"]').addClass('active');
  };

  // Icons drawer
  that.drawIcons = function() {
    var details = model.get('pollDetails');
    that.listContainer.html('');
    jQuery.each(details, function(index){
      var item = jQuery('<div/>')
          .addClass('icon')
          .attr('rel', index)
          .append(jQuery('<img/>').attr('src', this.thumbnail))
          .appendTo(that.listContainer)
          .click(function() { that.switchTo(index); } );
    });
  };

  that.setVoteMode = function(anon) {
    that.nameVote.removeClass('active');
    that.anonVote.removeClass('active');
    if(anon) {
      that.anonVote.addClass('active');
      that.form.hide();
    } else {
      that.nameVote.addClass('active');
      that.form.show();
    }
    model.setAnonMode(anon);
  };

  // Popup show
  that.showPopup = function() {
    that.blender.show();
    that.popup.show();
    that.form.show();
    that.nameVote.click(function(){that.setVoteMode(0);});
    that.anonVote.click(function(){that.setVoteMode(1);});
  };

  // Vote
  that.vote = function() {
    var anon = model.get('anonymous');
    if(anon) {
      model.vote(0,0);
    } else {
      var name = that.popupName.val();
      var email = that.popupEmail.val();
      var testExprName = /.{2,}/i;
      var testExprEmail = /[a-z0-9\.\_]{1,}@[a-z0-9\.\_\-]{2,}\.[a-z]{2,5}/i;
      if(! testExprName.test(name)) {
        that.popupNameLabel.addClass('error');
        return;
      } else {
        that.popupNameLabel.removeClass('error');
      }
      if(! testExprEmail.test(email)) {
        that.popupEmailLabel.addClass('error');
        return;
      } else {
        that.popupEmailLabel.removeClass('error');
      }
      model.vote(name, email);
    }
  }

  /*
   * Listening methods
   */
  // Model initialization
  model.PollUpdated.addObserver(function () {
    var details = model.get('pollDetails');
    var hasVote = model.get('hasVote');
    that.drawIcons();
    that.switchTo(0);
    that.category.html(details[0].category_name);
    if(hasVote == '1' || hasVote == 1) {
      that.voteBtn.hide();
    } else {
      that.voteBtn.click(that.showPopup);
      that.popupClose.click(function() {
        that.popup.hide();
        that.blender.hide();
      });
      that.popupVoteBtn.click(that.vote);
      gapi.plusone.render(that.google, {"size": "medium", "count": "true"});
    }
  });

  // Voted
  model.Voted.addObserver(function() {
    that.popup.hide();
    that.voteBtn.hide();
    that.popupThanks.show();
    that.popupThanksClose.click(function() {
      that.popupThanks.hide();
      that.blender.hide();
    });
  });

  // Got email error
  model.EmailError.addObserver(function() {
    that.popup.hide();
    that.voteBtn.hide();
    that.popupEmailError.show();
    that.popupEmailClose.click(function() {
      that.popupEmailError.hide();
      that.blender.hide();
    });
  });

};

/*******************************************************************************
 * Controller
 */
OMVC.VotingPollController = function (model, view, category) {
  model.initialize(category);
};






