//var BrandName = 'Dealfind';
//var BrandName = 'GroupClick';

function updateAffiliateLinkURL() {
	   
    var aff_key = $.cookie("MyAffiliateKey");
    //check if there is a= already, if not add the key
    if(typeof AffiliateLinkURL == "string"){
    	if(AffiliateLinkURL.length>0){
    		if(AffiliateLinkURL.indexOf("?a=")>0){
    		}else{
    			if(typeof aff_key == "string"){
    				AffiliateLinkURL+="?a="+aff_key;
    			}
    		}	
    	}
    }
}

function aFacebook_OnClick(e)
{ 
	var userName = $.cookie("loginUserName");
	//if( userName !="") LoggedIn = true;
	
	e.preventDefault();
  if(LoggedIn)
    ShareOnFacebook();
  else
    OfferToRegister(ShareOnFacebook);

}

var OfferToRegisterCallBack;

function OfferToRegister(CallBack)
{
	
  OfferToRegisterCallBack = CallBack;
  MessageBox('It\'s a good opportunity to Register and Make Money!', 'You are not logged in right now.'+
        ' This is a great opportunity to become a registered '+BrandName+' user - this will only'+
        ' take 2 minutes and you can start making money right away by sharing your unique Ambassador Link'+
        ' with your friends. <a href=/making-money-with-us.php target=_blank>Learn how some'+
        ' people are making a living with '+BrandName+'</a>.',
        'Sign Me Up!|Sign In|Share Without Making Money',
        OfferToRegister_ProcessAnswer, 0);
}

function OfferToRegister_ProcessAnswer(Answer)
{
	
  if(Answer==0)
    window.location = '/register.php';
  else if(Answer==1)
    window.location = '/sign-in.php';
  else if(Answer==2)
	  OfferToRegisterCallBack();
 
}


function ShareOnFacebook() { 
	
	FB.getLoginStatus(function(response) {
		  if (response.authResponse) { 
		    PostOnUserWall();
		  } else {
			  updateAffiliateLinkURL();
			 // alert ( AffiliateLinkURL );
			  Popup('http://www.facebook.com/sharer.php?u='+urlencode(AffiliateLinkURL)+'&t='+
				        urlencode(DealName), 640, 480);
		  } 
	});
	
}

function PostOnUserWall() {
	updateAffiliateLinkURL();
	FB.ui({
			    method: 'feed',
			    name: DealName,
			    link: AffiliateLinkURL,
			    picture: DealFacebookThumbnailURL,
			    caption: ShareOnFacebookCaption,
			   // description: UserMessagePrompt,
			    properties: {
	                'Regular price': RegularPriceHTML,
	                'Our price': OurPriceHTML,
	                'You save': YouSaveHTML
	                },
	            actions: [{name: 'Read more',link:AffiliateLinkURL}]    
			  },
			  function(response) {
			    if (response && response.post_id) {
			     
			    } 
			  });
}


function shareAmbassadorLinkOnFB(AffiliateLinkURL) {
	//updateAffiliateLinkURL();
	FB.ui(
			{
	    method: 'feed',
				name: 'Dealfind.com',
				link: AffiliateLinkURL 
	    } 
	  	);
}

function shareAmbassadorLinkOnTwitter(AffiliateLinkURL) { 
	
	 var URL = '/misc/json-shorten-url.php?URL='+urlencode(AffiliateLinkURL);

	  $.getJSON(URL, function(data) {
	    if(data['ErrorMsg'] || data['ShortURL'] == null)
	    {
	    	Popup('http://twitter.com/home?status='+AffiliateLinkURL,800,480);
	    }
	    else
	    {
	    	URL = data['ShortURL'];
	    	Popup('http://twitter.com/home?status='+URL,800,480);
	    }
	   
	  });  

	
	
}


function ShareOnFacebookOld()
{
  FB.Connect.get_status().waitUntilReady(function(status){ 
    if(status==FB.ConnectState.connected || status==FB.ConnectState.appNotAuthorized)
      FB_Connect_StreamPublish();
    else
      Popup('http://www.facebook.com/sharer.php?u='+urlencode(AffiliateLinkURL)+'&t='+
        urlencode(DealName), 640, 480);
  });
}

var ShareOnFacebookCaption = '{*actor*} thinks you should check out this awesome deal at '+BrandName+'.';
var UserMessagePrompt = 'Share this deal with your friends and make money!';

function FB_Connect_StreamPublish()
{
	updateAffiliateLinkURL();
  var attachment = {
        'name': DealName,
        'href': AffiliateLinkURL,
        'caption': ShareOnFacebookCaption,
        'properties': {
                'Regular price': RegularPriceHTML,
                'Our price': OurPriceHTML,
                'You save': YouSaveHTML
                },
        'media': [{ 'type': 'image', 'src': DealFacebookThumbnailURL, 'href': AffiliateLinkURL}]
        };
  var action_links = [{'text': 'Read more', 'href': AffiliateLinkURL}];
  var target_id = null;
  var user_message_prompt = UserMessagePrompt;
  var callback = null;
  var auto_publish = false;
  var actor_id = null;
  FB.Connect.streamPublish('', attachment, action_links, target_id, user_message_prompt,
        callback, auto_publish, actor_id);
}

function aTwitter_OnClick(e)
{	
	var userName = $.cookie("loginUserName");
	//if( userName !="") LoggedIn = true;
	
	e.preventDefault();
	if(LoggedIn){
	  ShareOnTwitter();
  }else {
	  OfferToRegister(ShareOnTwitter);
  }
}

function ShareOnTwitter()
{
 
  if($('#aTwitter').attr('href')=='#' || $('#aTwitter').attr('href')=='#twitter' || $('#aTwitter').attr('href')=='#share-on-twitter')
	  ShortenURLForTwitter();
  else
    OpenTwitterPopup();
}

function OpenTwitterPopup()
{
  Popup($('#aTwitter').attr('href'), 800, 480);
}

function aEmail_OnClick(e)
{
  if(LoggedIn)
    if(LoggedUserEmail>'')
    {
      MessageBox('Share this deal via e-mail', '#frmEmail', 'Send E-mail|Cancel', null, 0, SendEmail);
      $('#EmailTo').focus();
    }
    else
      MessageBox('Please specify your e-mail', 'We don\'t have your e-mail address. Please enter'+
        ' your e-mail address on <a href=/my/profile.php>My Profile</a> page to share deals via e-mail.',
        'OK');
  else
    MessageBox('Please Register first', 'You are not signed in right now. Please'+
        ' <a href=/register.php>Register a '+BrandName+' account</a> first - it will only take you a'+
        ' couple of minutes and it ensures that we protect users from spam.', 'OK');
  e.preventDefault();
}

function SendEmail(Answer)
{
  if(Answer==0)
  {
    if(!CheckListOfEmails('EmailTo')
       || !CheckString('EmailSubject', 'E-mail Subject', 2, 100))
      return false;
    ShowFormOverlay();
    var URL = '/misc/json-share-deal-via-email.php';
    var PostData = {
        DealID: DealID,
        To: $('#EmailTo').val(),
        Subject: $('#EmailSubject').val(),
        Notes: $('#EmailNotes').val()
        };
    $.post(URL, PostData, function(data)
    {
      HideFormOverlay();
      if(data['ErrorMsg'])
      {
        $('#EmailTo').focus();
        alert('Error: '+data['ErrorMsg']);
      }
      else
      {
        MessageBox_Close();
        var s = 'E-mail has been sent successfully. Thank you for using '+BrandName+
                ' services and for spreading the word! Your friends will think you are cool (we'+
                ' definitely think you are)';
        if(AffiliatePayout && AffiliatePayout>0)
          s += ', plus we will pay you <b>'+
          		MoneyStringTrimDecimalZeros(AffiliatePayout)+'</b> for every purchase they make through your'+
                ' Ambassador link. With '+BrandName+', <i>everybody wins</i>.';
        else
          s += ', but there\'s more - learn <a href=/making-money-with-us.php>how to make'+
                ' money with '+BrandName+'</a>, it\'s super-easy.';
        MessageBox('Thank you!', s, 'OK');
      }
    }, 'json');
    return false;
  }
  return true;
}

var aTwitter_Clicked = false;
var bitly_URL = null;

function ShortenURLForTwitter()
{
	/*check if bitly URL is set*/
	if(bitly_URL == null){
		if(document.location.protocol=='https:'){
			ShortenViaAjaxRequestToServer();
		}else {
			ShortenViaBitLy();
		}
	}else{
		/*run pop-up*/
		SetTwitterHref(bitly_URL);
		OpenTwitterPopup();
	}
}

function ShortenViaAjaxRequestToServer()
{
  var URL = '/misc/json-shorten-url.php?DealID='+DealID;
//  alert(URL);
  $.getJSON(URL, function(data) {
    if(data['ErrorMsg'] || data['ShortURL'] == null)
    {
//      alert('Cannot shorten URL for Twitter... Please refresh the page.');
    	SetTwitterHref(null);
    }
    else
    {
    	bitly_URL = data['ShortURL'];
    	SetTwitterHref(bitly_URL);
    }
    /*run pop-up*/
    OpenTwitterPopup();
  });  
}

function SetTwitterHref(ShortURL)
{
	/*if ShortURL is null use full length URL*/
	updateAffiliateLinkURL();
	if(ShortURL == null){
		ShortURL = AffiliateLinkURL;
	}
	
	$('#aTwitter').attr('href', 'http://twitter.com/home?status='+urlencode(GetStringBeginningWithEllipsis(DealName, 140-ShortURL.length-1)+' '+ShortURL));
	//if(aTwitter_Clicked)
		//OpenTwitterPopup();
}

function ShortenViaBitLy()
{
	updateAffiliateLinkURL();
  var login = 'groupclick';
  var apiKey = 'R_cff114d8206c70cd34365ff3aadbd80e';
  var bitlyurl = 'http://api.bit.ly/shorten?version=2.0.1&login='+
        login + '&apiKey=' + apiKey + '&longUrl=' + AffiliateLinkURL;
  
  $.ajax({
      url: bitlyurl,
      type: 'GET',
      dataType: 'jsonp',
      error: function(xhr, status, error) {
    	  SetTwitterHref(null);
    	  /*run pop-up*/
    	  OpenTwitterPopup();
      },
      success: function(data) {
    	  var bitlylink = null;
          for(var r in data.results)
          {
            bitlylink = data.results[r]['shortUrl'];
            break;
          }
          
          /*check if bitlylink has been set*/
          if(bitlylink != null)
          {
          	bitly_URL = bitlylink;
          	SetTwitterHref(bitly_URL);
          } else{  
        	SetTwitterHref(null);        	  
          }
          /*run pop-up*/
          OpenTwitterPopup();
      }
  }); 
}

