(function($){
  window.ga_track = function (tag, type, optional_label, optional_value){
    window._gaq = _gaq || [];
    _gaq.push(["_trackEvent", tag, type, optional_label, optional_value]);
  };
  getUrlVars = function(url){
    url = url ? url : window.location.href;
    var vars = [], hash;
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  };
  getUrlVar = function(name,url){
    return this.getUrlVars(url)[name];
  };

  isInternalRedirect = function(url) {
    url = decodeURIComponent(url);
    var dummy_anchor = document.createElement('a');
    dummy_anchor.href = url;
    var is_valid_protocol = /http(s)?:$/.test(dummy_anchor.protocol);
    var is_valid_hostname = (new RegExp('^' + location.hostname + '$')).test(dummy_anchor.hostname);
    return (is_valid_protocol && is_valid_hostname);
  };

  is_abbr = function (e){
    return ((getUrlVar('download_id', e) && getUrlVar('download_id', e).length > 0) ||
            getUrlVar('abbr', e) == 'true' || getUrlVar('from',e) == 'download');
  };
  var atStep = 1;
  slideshare_object.setup_signup_modal_box = function(){
    $('a[href*="/login"], a[href*="/signup"]').filter(':not(.void_fancybox)').fancybox({
      'frameWidth'          : 650,
      'frameHeight'         : 400,
      'hideOnContentClick'  : false,
      'enableEscapeButton'  : true,
      'centerOnScroll'      : false,
      'fromType'            : null,
      'fromSource'          : null,
      'thisLink'            : null,
      'callbackOnStart'     : function (e){
        thisLink = e.href;
        atStep = 1;
        if( is_abbr(thisLink) ) {
          window.ga_track( "Signup", "thickbox_loading", "download" );
        } else {
          window.ga_track( "Signup", "thickbox_loading" );
        }
        return true;
      },
      'callbackOnShow'      : function (e){
        $('#fancy_outer').animate({
          top: $(document).scrollTop() + 40});
        if( is_abbr(thisLink) ) {
          window.ga_track( "Signup", "thickbox_loaded", "download" );
        } else {
          window.ga_track( "Signup", "thickbox_loaded" );
        }

        modalMessages = {
          '_start'    : "Login or Signup to ",
          'download'  : "download this file",
          'addcontact': "follow this user",
          'favorite'  : "favorite this document",
          'comments'  : "post a comment",
          'AddToCommunity': "add this document to a group/event",
          'follow'    : "follow this user",
          'business'  : "try LeadShare",
          'upload'    : "start uploading",
          'contest'   : "vote",
          'rsvp'      : "join this meeting",
          '_end'      : ""
        };
      
        if ( !e || !e.href || e.href.length < 1) {
          $('#modal_message').hide();
        } else {
          fromType   = getUrlVar('from', e.href);
          fromSource = getUrlVar('from_source', e.href);
          if( !fromType || fromType.length < 1 || !modalMessages[fromType] || modalMessages[fromType].length < 1 ){
            $('#j-signup-notice').hide();
          } else {
            $('#j-signup-notice').html(modalMessages._start+modalMessages[fromType]+modalMessages._end);
          }
        }
        return true;
      },
      'callbackOnClose'     : function (e){
        if( is_abbr(thisLink) ) {
          window.ga_track( "Signup", "thickbox_closed", "download" );
        } else {
          window.ga_track( "Signup", "thickbox_closed" );
        }
      
        return true;
      },
      'easingIn'            : 'linear',
      'easingOut'           : 'linear',
      'easingChange'        : 'linear',
      'dontSetNavigation'   : true,
      'dontShowFancyTitle'  : true
    });
  };
  window.modal_login = {};
  modal_login.cache_validations = {
    username  : false,
    password  : false,
    email     :false,
    section_one : false
  };
  
  window.modalSignupCallBack = function(){
    var form_1 = $('#signup_form_1');
    var element = null;
    window.ga_track( "Signup", "thickbox_signup_success" );
    element = form_1.find('.submitFormButton .modal-action-message').html("Signup is successful!");
    element.removeClass('modal-action-fail hide').addClass('modal-action-success');
  
    if ( fromType !== 'business' || !fromSource || fromSource.length < 1 || !isInternalRedirect(fromSource) ) {
      window.location.reload();
    } else {
      window.location.href = decodeURIComponent(fromSource);
      $(window).trigger('submitPaymentForm');
    }
  };
  
   window.modalLoginCallBack = function(){
    if( is_abbr(window.thisLink) ) {
      _gaq.push(['_trackEvent', 'Login', 'ss_login', 'ss_login_from_fancybox(download)']);
    } else {
      _gaq.push(['_trackEvent', 'Login', 'ss_login', 'ss_login_from_fancybox']);
    }
    var escapeUrl = jQuery.inArray(window.fromType, ["business", "upload", "download"])  !== -1;
    if(window.fromType == 'unsubscribe') {
      $.post('/comment/unsubscribe' , {'id' : slideshare_object.slideshow.id}, 
      function(response_data) {
        $('#fancy_close').click();
        $('.comments-unsubscribe').hide();
        $('.comments-subscribe').show().highlightOut();
        $('.comments-subscribe input')[0].checked = false;
        window.location.href= window.location.origin + window.location.pathname;
      });
    } else if(escapeUrl && window.fromSource && window.fromSource.length > 1 && isInternalRedirect(window.fromSource)) {
      window.location.href = decodeURIComponent(window.fromSource);
      $(window).trigger('submitPaymentForm');
    } else {
      window.location.reload() ;
    }
   };
  //jQuery.receiveMessage( callback [, source_origin ] [, delay ] );
  // callback (Function) executes whenever a jQuery.postMessage message is received, 
  // source_origin (String) If window.postMessage is available and this value 
  //is not equal to the event.origin property, the callback will not be called.
  // delay  (Number) An optional zero-or-greater delay in milliseconds .
    if ($.isFunction($.receiveMessage)) {
      $.receiveMessage(
        function(event){
          iframe_height = $('#iframe_login').height();
          fancy_outer_height = $('#fancy_outer').height();
          if(event.data === 'modalLoginSubmit'){
            modalLoginCallBack();
          }else if(event.data === 'modalSignupSubmit' ){
            modalSignupCallBack();
          }else if(event.data === 'signup_expand' ){
            $('#modal_signup').slideDown('slow');
            $('#fancy_outer').animate({
              height:'+=180'
            });
            $('#iframe_login').height(iframe_height + 180);
          }else if(event.data === 'signup_shrink' ){
            $('#modal_signup').slideUp('slow');
            $('#fancy_outer').animate({
              height:'-=180'
            });
            $('#iframe_login').height(iframe_height - 180);
          }else if(event.data === 'hideSpinner'){
            $('.spinner').hide();
            $('#iframe_login').show();
          }
        },(function(){
              return 'https://'+$(location).attr('host');
            }()
          )
      );
    }
  
  $('#signup_username').live('change',function() {
    if( is_abbr(thisLink) ) {
      window.ga_track("Signup", "thickbox_formstart", "download");
    } else {
      window.ga_track("Signup", "thickbox_formstart");
    }
  });
  $('.fb_button_text').live('click',function() {
      window.ga_track("Signup", "fancybox_fblogin_clicked");
  });
  $(document).ready(function(){
    _gaq.push(['_setAccount', 'UA-2330466-1']);
    _gaq.push(['_setDomainName', '.slideshare.net']);
    slideshare_object.setup_signup_modal_box();
  });
})(jQuery);
