﻿// Register the namespace
registerNS("Iminos.Friends.Invite");

// Initialize the variables
Iminos.Friends.Invite.dt = null;
Iminos.Friends.Invite.cid = null;
Iminos.Friends.Invite.cid64 = null;
Iminos.Friends.Invite.httpRequest = null;

//var myUrls= [[["myUrl",strings["Mynewalbumweblink"],strings["Helloyoucanv"]]],[["photoet.com",strings["Recommendphotoetcom"],strings["Helloyoucangetfree3Dpage"]]],[["iminos.com",strings["Recommendiminoscom"],strings["Higetfreewebspacehosting"]],[["acezip.net",strings["Recommendacezip"],strings["Higetfreeware"]]]];

var myUrls= [["myUrl",strings["Mynewalbumweblink"],strings["Helloyoucanv"]],["photoet.com",strings["Recommendphotoetcom"],strings["Helloyoucangetfree3Dpage"]],["iminos.com",strings["Recommendiminoscom"],strings["Higetfreewebspacehosting"]],["acezip.net",strings["Recommendacezip"],strings["Higetfreeware"]]];

var curIndex=0;

// build a base url to open a popup
// normally it would be fixed but because this sample can be applied anywhere
// we do it this way
Iminos.Friends.Invite.baseURL = window.location.href.toString();
if(Iminos.Friends.Invite.baseURL.indexOf('/index.php') > -1)
{
	if (Iminos.Friends.Invite.baseURL.indexOf('?') > -1){
	Iminos.Friends.Invite.baseURL = Iminos.Friends.Invite.baseURL.substring(  0,location.href.indexOf("?"))
  };
  //alert(Iminos.Friends.Invite.baseURL);
  Iminos.Friends.Invite.baseURL = Iminos.Friends.Invite.baseURL.replace('/index.php', '/');
}

Iminos.Friends.Invite.BuildUrl = function(Offer)
{
	var _ReturnURI = Iminos.Friends.Invite.baseURL + "livedelegation-handler.php";
	_ReturnURI = _ReturnURI.replace("#", "");

	var _PrivacyStatement = _ReturnURI.replace("livedelegation-handler.php", "privacy.php");
	var _PermissionRequestURI = "https://consent.live.com/Delegation.aspx?RU=" + (_ReturnURI) + "&ps=" + (Offer) + "&pl=" + (_PrivacyStatement);

	return _PermissionRequestURI;
}

// The function that gets executed when clicking the start-button
// it shows a waiting icon and opens a popup
Iminos.Friends.Invite.StartInvite = function()
{
	document.getElementById("invitepageContents").innerHTML = "<p>"+strings["inviteStarted"] +"<a href=\"#\" onclick=\"return Iminos.Friends.Invite.StartInviteAttempt2()\">"+strings["ClickHere"]+"</a>.</p>"+ Iminos.Friends.Invite.BuildWaitingMessage(strings["waitForConsent"]);
	window.open(Iminos.Friends.Invite.BuildUrl("Contacts.View"));
	
	return false;
}

// This function is executed the 2nd time a user clicks the start-button,
// should a popup blocker have stopped him from his first attempt
Iminos.Friends.Invite.StartInviteAttempt2 = function()
{
	document.getElementById("invitepageContents").innerHTML = "<p>"+strings["inviteStartedAttempt2"]+"</p>" + Iminos.Friends.Invite.BuildWaitingMessage(strings["waitForConsent"]);
	window.open(Iminos.Friends.Invite.BuildUrl("Contacts.View"));

	return false;
}

// display a waiting indicator
Iminos.Friends.Invite.BuildWaitingMessage = function(message)
{
	var waitingMsg = "<p class=\"inviteCenter\"><img src=\""+tplroot+"/img/loading.gif\" width=\"31\" height=\"31\" alt=\""+strings["Pleasewait"]+"\"><br />"+message+"</p>";

	return waitingMsg;
}

// this function is executed when consent has been given
Iminos.Friends.Invite.ConsentGiven = function()
{
	document.getElementById("invitepageContents").innerHTML = "<p>"+strings["fetchingContacts"]+"</P>" + Iminos.Friends.Invite.BuildWaitingMessage(strings["waitForContacts"]);
	Iminos.Friends.Invite.getContacts();
}

// the user has refused to give his consent, show him an error message and tell him what he can do
Iminos.Friends.Invite.ConsentRefused = function()
{
	var outputtxt = "<p>"+strings["consentRefused"]+"</p>";
	outputtxt += "<p class=\"inviteCenter\"><button type=\"button\" class=\"inviteBtn\" onclick=\"location.reload()\">" + strings["tryAgain"] + "</button></p></form>";
	
	document.getElementById("invitepageContents").innerHTML = outputtxt;
}

// this function gets contacts from the server, by passing it a delegation token (dt) and location id (cid)
Iminos.Friends.Invite.getContacts = function()
{
	if (window.XMLHttpRequest)
	{ // Mozilla, Safari, ...
		Iminos.Friends.Invite.httpRequest = new XMLHttpRequest();
		if (Iminos.Friends.Invite.httpRequest.overrideMimeType)
		{
			Iminos.Friends.Invite.httpRequest.overrideMimeType('text/plain');
			// See note below about this line
		}
	}
	else if (window.ActiveXObject)
	{ // IE
		try
		{
			Iminos.Friends.Invite.httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				Iminos.Friends.Invite.httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {}
		}
	}

	if (!Iminos.Friends.Invite.httpRequest)
	{
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	Iminos.Friends.Invite.httpRequest.onreadystatechange = function() { Iminos.Friends.Invite.processContacts(); };

	var poststring = 'dt='+Iminos.Friends.Invite.dt;
	poststring += '&cid='+Iminos.Friends.Invite.cid;

	Iminos.Friends.Invite.httpRequest.open('POST', siteroot+'/contacts.php' , true);
	Iminos.Friends.Invite.httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	Iminos.Friends.Invite.httpRequest.setRequestHeader("Content-length", poststring.length);
	Iminos.Friends.Invite.httpRequest.setRequestHeader("Connection", "close");
	Iminos.Friends.Invite.httpRequest.send(poststring);
	
	// fire the ajax request, start requesting contacts
}

// process the request from the server
Iminos.Friends.Invite.processContacts = function()
{
	if (Iminos.Friends.Invite.httpRequest.readyState == 4)
	{
		if (Iminos.Friends.Invite.httpRequest.status != 200)
		{
			alert('There was a problem with the request.');
		}
		else
		{
			var resptxt = Iminos.Friends.Invite.httpRequest.responseText;
			
			// is it an error, yes or no?
			if(resptxt.substring(0,5) == "error")
			{
				Iminos.Friends.Invite.errorOccured(resptxt);
			}
			else
			{
			  //alert("001resptxt "+resptxt);
				Iminos.Friends.Invite.parseContacts(resptxt);
				//Adding title and content from the strings
			  
	      emailText();
       }
		}
	}
}
function emailText()
{
//Get user's browser's language
if (navigator.appName == 'Netscape')
var curlanguage = navigator.language;
else
var curlanguage = navigator.browserLanguage;
myfrm.myLanguage.value = curlanguage;
//
   var newUrl = document.referrer;
 var newUrlb = location.href.substring(location.href.indexOf("=")+1,location.href.length)
   if (newUrl=="") 
 {
    if (location.href.indexOf("?document.referrer=")>-1 )
   {
   for (var i = 1;i<=myUrls.length-1;i++) 
        {
          if (newUrlb.match(myUrls[i][0]))
            {
             
              myfrm.title.value = myUrls[i][1];
              myfrm.content.value = myUrls[i][2];
              
           	};
	      }
   }else if (location.href.indexOf("?")>-1 && location.href.indexOf("file:///")==-1)
   {
  
   myfrm.title.value = myUrls[0][1];
   myfrm.content.value = myUrls[0][2]+ newUrlb+" !";
   }else{
   myfrm.title.value = strings["title"];
   myfrm.content.value = strings["content"];
   }
 } else 
   {
     for (var i = 1;i<=myUrls.length-1;i++) 
        {
          if (newUrl.match(myUrls[i][0]))
            {
             
              myfrm.title.value = myUrls[i][1];
              myfrm.content.value = myUrls[i][2];
              
           	};
	      }
   }
};
// display the list of contacts on screen, this also builds the form used to submit the contacts to the server

function chkinput(form)
  {
    /*if(form.from.value=="")
	 {
	   alert(strings["inputYourEmailAddress"]);
	   form.from.select();
	   return(false);
	 }*/
     if(form.title.value=="")
	 {
	   alert(strings["inputYourSubject"]);
	   form.title.select();
	   return(false);
	 }
	 if(form.content.value=="")
	 {
	   alert(strings["inputYourMessage"]);
	   form.content.select();
	   return(false);
	 }
    return(true);
  }

function curlang(){
if (navigator.appName == 'Netscape')
var curlanguage = navigator.language;
else
var curlanguage = navigator.browserLanguage;
return curlanguage;
};

Iminos.Friends.Invite.parseContacts = function(resptxt)
{
	document.getElementById("invitepageContents").innerHTML =  Iminos.Friends.Invite.BuildWaitingMessage("Parsing contacts");

	// processing
	
	var newUrla = document.referrer;
   if (newUrla=="") 
{
      if (location.href.indexOf("?")>-1 && location.href.indexOf("file:///")==-1){
      var newUrlb = location.href.substring(location.href.indexOf("=")+1,location.href.length)
      var newTitle = strings["PageTitle"].replace("this site",newUrlb);
           // document.write("<p>"+newTitle+"</p>");
      }else {
      var newTitle = strings["PageTitle"]
      }
} else 
  {
     for (var i = 1;i<=myUrls.length-1;i++) 
        {
          if (newUrla.match(myUrls[i][0]))
            {
      var newTitle = strings["PageTitle"].replace("this site",myUrls[i][0]);
        //    document.write("<p>"+newTitle+"</p>");
            break;
           	}
	      }

};

	var outputtxt = "<form name=myfrm action=\"invitecontacts.php\" onsubmit=\"return chkinput(this)\" method=\"POST\">" + "<p>"+newTitle+"<br>"+strings["selectContacts"]+"</p>";
	outputtxt += "<div id=\"contactsInviteList\">"+resptxt+"<hr>   <br><input type=\"hidden\" name=\"myLanguage\" size=\"50\" class=\"inputcss\"><tr><td height=\"25\"><div align=\"left\" class=\"emailcss\">&nbsp;"+strings["mySubject:"]+"</div></td>  <td height=\"25\">&nbsp;<input type=\"text\" name=\"title\" size=\"50\" class=\"inputcss\" ></td>  </tr>  <tr>  <td height=\"100\"><div align=\"left\" class=\"emailcss\">&nbsp;"+strings["myMessage"]+"</div></td>  <td height=\"50\">&nbsp;<textarea name=\"content\" rows=\"8\" cols=\"50\" class=\"inputcss\"></textarea></td>  </tr>  <td height=\"30\" colspan=\"2\"><div align=\"center\">  <input type=\"reset\" value=\"Reset\" class=\"buttoncss\"></div></td>"+"</div>";
  //<tr><td width=\"100\" height=\"25\"><div align=\"left\"  class=\"emailcss\">&nbsp;"+strings["myFrom"]+"</div></td>  <td width=\"350\">&nbsp;<input type=\"hidden\" name=\"from\" size=\"50\" class=\"inputcss\" ></td>  </tr> 
  //<input type=\"text\" name=\"myLanguage\" size=\"50\" class=\"inputcss\" value=\"return curlang\">
  
  

	outputtxt += "<p class=\"inviteCenter\"><button type=\"submit\" class=\"inviteBtn\">" + strings["continue"] + "</button></p></form><br>";
	
	document.getElementById("invitepageContents").innerHTML = outputtxt;
	
	//alert("003outputtxt "+outputtxt);
}

// something has gone wrong, inform the user
Iminos.Friends.Invite.errorOccured = function(resptxt)
{
	var errorcode = resptxt.split("|");
	var outputtxt = "<p>" + strings["anErrorOccured"];
	outputtxt += errorcode[2];
	outputtxt += " (code " + errorcode[1] + ")";
	outputtxt += "</p>";
	
	outputtxt += "<p class=\"inviteCenter\"><button type=\"button\" class=\"inviteBtn\" onclick=\"location.reload()\">" + strings["tryAgain"] + "</button></p></form>";
	
	document.getElementById("invitepageContents").innerHTML = outputtxt;
}

// this function toggles a checkbox
Iminos.Friends.Invite.toggleCheckbox = function(chkId)
{

	for (var i=0;i<=chkId;i++)
 {
	var chkbox = document.getElementById('chkCtc'+i);

	if(chkbox.checked)
	{
		chkbox.checked = false;
	}
	else
	{
		chkbox.checked = true;
	};
 }
}
// this function toggles a single checkbox
Iminos.Friends.Invite.toggleCheckboxSingle = function(chkId)
{
	var chkbox = document.getElementById('chkCtc'+chkId);

	if(chkbox.checked)
	{
		chkbox.checked = false;
	}
	else
	{
		chkbox.checked = true;
	};
}


