﻿var MyBetaList =
{
  // Properties
  isSubmitted: false,
  defaultEmailAddress: 'آدرس ايميل',
  referral: null,
  emailRegex: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
  url: null,
  
  init: function()
  {
    // Check if HEAD and BODY are present
    if(document.getElementsByTagName('head').length == 0 || document.getElementsByTagName('body') == 0)
    {
      alert('Please make sure your page has at least a HEAD and BODY element or My Beta List will not work.');
      // @TODO: create HEAD and BODY elements
    }
 
    MyBetaList.getScript('https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function() { MyBetaList.checkUser(); } );
  },
  
  checkUser: function()
  {
    // Ensure there's no jQuery conflict
    jQuery.noConflict();
    
    if(MyBetaList.url == null)
    {
      // Retrieve location href (without the referral parameter)
      if(window.location.href.indexOf('?') != -1)
        MyBetaList.url = window.location.href.substring(0, window.location.href.indexOf('?'));
      else
        MyBetaList.url = window.location.href;
    }
    
    // Rename myself so the actual widget can be called #MyBetaList (easier for custom CSS)
    jQuery('#MyBetaList').attr('id', 'MyBetaList-js');
    jQuery('#MyBetaList-js').after('<div id=\'MyBetaList\'>  <div id=\'MyBetaList-step1\'>       <form id=\'MyBetaList-form\' method=\'post\'> <table class=\'tblEnterEmail\'><tr><td><table cellpadding=\'0\' cellspacing=\'0\' border=\'0\' height=\'52\'><tr><td><img src=\'Images/Textbox-Right.gif\'/></td><td class=\'tdEmailTextBox\'><input id=\'MyBetaList-email\' name=\'MyBetaList-email\' type=\'text\' value=\'آدرس ايميل\' class=\'TextBox\' /></td><td><img src=\'Images/Textbox-Left.gif\'/></tr></table></td><td><input type=\'submit\' value=\'\' class=\'Button\' /></td></tr></table></form>  </div>  <div id=\'MyBetaList-step2\' style=\'display: none; width:410px;padding-left:10px;\'>   <p><span class="breifDesc">برنده يك <span class="ipad">iPad 2</span> شويد!</span><br /><br /><span style=\'text-align: justify;\'>براي افزايش شانس خود به منظور برنده شدن يك iPad 2،&nbsp; لينك اختصاصي &nbsp;خود (لينك زير) را با دوستانتان به اشتراك بگذاريد. به ازاي هر ايميل وارد شده شانس برنده شدن شما افزايش مي يابد. </span><br /><br />به همين سادگي. با ثبت نام هر يك از دوستان شما، شانس  شما بالا خواهد رفت. موفق باشيد!</p>    <span style=\'background-color:Transparent;\' id=\'MyBetaList-referrer-link-wrap\' ><div class=\'urlBackground\'><div style="text-align:center; padding-top:14px; padding-bottom:18px; font-weight:bold; font-size:13px;">لينك اختصاصي شما</div><a href=\'#\' id=\'MyBetaList-referrer-link\'>&nbsp;</a><div style="text-align:center; padding-top:20px;"><img src="Images/Email-To-friends.gif" onclick="OpenWindow()" class="Hand" /></div></div>  </span>  </div></div>');
    
    // Check if returning subscriber
    if(false)
    {
      // Show step 2
      MyBetaList.showStep2(MyBetaList.url+'?r=');
    }
    else
    {
      // New subscriber, set up form
      MyBetaList.setupForm();
    }
  },
  
  showStep2: function(referral_link)
  {    
    // Set referral link
    jQuery('#MyBetaList-referrer-link').attr('href', referral_link);
    jQuery('#MyBetaList-referrer-link').html(referral_link);

    // Hide step 1
    jQuery('#MyBetaList-step1').hide();
    jQuery('#MyBetaList-message').hide();
    jQuery('#MyBetaList-title').hide();

    // Show step 2
    // jQuery('#MyBetaList-step2').append('<a style="display: block; float: left; border-bottom:0px;text-decoration:none;" id="MyBetaList-tweet" href="http://twitter.com/share" class="twitter-share-button" data-count="none" data-text="Welcome to eTak.ir - We want to be the new way you shop in Iran. We will be online soon." data-url="'+referral_link+'" data-via="eTakIran" data-related="betalist:Discover and get access to early-stage startups">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>');
   // jQuery('#MyBetaList-step2').append('<iframe src="//www.facebook.com/plugins/like.php?href='+encodeURIComponent(referral_link)+'&amp;layout=button_count&amp;show_faces=false&amp;width=80&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:21px; margin-left: 5px" allowTransparency="true"></iframe>');            
    jQuery('#MyBetaList-step2').show();
    jQuery('#MyBetaList-Share').show();
    jQuery('#MyBetaList-Thanks').show();
    
  },
  

  
  setupForm: function()
  {
    // Retrieve referral code
    MyBetaList.retrieveReferral();
    
    // Empty email field on focus
    jQuery('#MyBetaList-email').live('focus', function(event) {
      if(jQuery('#MyBetaList-email').val() == MyBetaList.defaultEmailAddress)
        jQuery('#MyBetaList-email').val('');
    });

    // Set back default email address on empty blur
    jQuery('#MyBetaList-email').live('blur', function(event) {
      if(jQuery.trim(jQuery('#MyBetaList-email').val()) == '')
        jQuery('#MyBetaList-email').val(MyBetaList.defaultEmailAddress);
    });

    // Handle form submission
    jQuery('#MyBetaList-form').live('submit', function(event) {
      
      // Prevent actual submission
      event.preventDefault();

      // Only handle a correct submission
      if(
        MyBetaList.isSubmitted ||                                               // check if form hasn't been submitted before
        jQuery('#MyBetaList-email').val() == MyBetaList.defaultEmailAddress ||  // check if it's not the default email address
        jQuery.trim(jQuery('#MyBetaList-email').val()) == '' ||                       // check if email address isn't empty
        !MyBetaList.emailRegex.test(jQuery('#MyBetaList-email').val())           // check if it's indeed a valid email address
      )
      {
        // Don't submit the form
      }
      else
      { 
        // Disable form
        MyBetaList.isSubmitted = true;
        jQuery('input', this).attr('disabled', 'disabled');

        // Set up JSON paramaters
        params = {
          token:            "3b3wga2o6",
          referrer_token:   MyBetaList.referral, 
          email:            jQuery('#MyBetaList-email').val(),
          location:         MyBetaList.url
        };

        // Send email address
        // @TODO: Use callback? (XSS)
        jQuery.getJSON('http://my.betali.st/subscribe?callback=?', params, function(data) {
          if(data.result)
          {
            // Show step 2
            MyBetaList.showStep2(data.result);
          }
          else
          {
            // Something went wrong (e.g. non-existing token)
            alert('Whoops. Couldn\'t add new subscriber. Please contact site owner.');
          }
        });

      }

    });
  },
  
  // @TODO: Simplify code
  retrieveReferral: function()
  {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    
    MyBetaList.referral = vars['r'];
  },
  
  getScript: function(url, success)
  {
    var script = document.createElement('script');
    script.src = url;

    var head = document.getElementsByTagName('head')[0],
    done = false;

    // Attach handlers for all browsers
    script.onload = script.onreadystatechange = function() {

      if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
        done = true;

        // callback function provided as param
        success();

        script.onload = script.onreadystatechange = null;
        head.removeChild(script);
      };
    };
    head.appendChild(script);
  }

};

MyBetaList.init();
