/*
 * Variables
*/
BASE_DOMAIN = "http://app.wodhopper.com/";
XSS_BASE_DOMAIN = BASE_DOMAIN.substring(0,BASE_DOMAIN.length-1); //Must strip out the final slash for the XSS to properly resolve to the host.
var split_url = window.location.href.split("/");  //splitting http://xxx.com results in [0]=http: [1]='' [2]=restOfBaseUrl
var parent_url = split_url[0] + "//" + split_url[2];

imComingTab = 0;
whosComingTab = 1;
ROOT_TAB_PARAMS = "xd="+parent_url;
iOSMobileUrl = BASE_DOMAIN+"iPhoneRsvp/index.html";
webMobileUrl = BASE_DOMAIN+"resources/mobileRsvp.html";
var isIPhone = false;
var isBlackBerry = false;
var isOtherMobile = getIsOtherMobile();
var firstTimeSession = 0;

rootTabsUrl = BASE_DOMAIN+"resources/wodhopper_widget_root.html"+"?"+ROOT_TAB_PARAMS;
var wodhopper_window = null;
var html_doc = document.getElementsByTagName('head').item(0);
var script = document.createElement("script");
var script2 = document.createElement("script");
var cssFile=document.createElement("link");
var cssFile2=document.createElement("link");
/*
 * Dynamic JQuery and other JS and CSS files
*/
cssFile.setAttribute("rel", "stylesheet");
cssFile.setAttribute("type", "text/css");
cssFile.setAttribute("href", BASE_DOMAIN+"css/feedbackBadge.css");
html_doc.appendChild(cssFile);

cssFile2.setAttribute("rel", "stylesheet");
cssFile2.setAttribute("type", "text/css");
cssFile2.setAttribute("href", BASE_DOMAIN+"css/custom-theme/jquery-ui-1.8.13.custom.css");
html_doc.appendChild(cssFile2);

script.type = "text/javascript";
script.src = BASE_DOMAIN+'js/jquery-1.5.1.min.js';
//IE:
if(window.attachEvent && document.all) {
    script.onreadystatechange = function () {
        if(this.readyState === "complete" || this.readyState === "loaded") {
            callback_function(); //execute
        }
    };
}
//other browsers:
else {
    //Since BB does not honor the .onload function for script tag
    //Place a timeout call to the callback function if it is a BlackBerery
    if(navigator.userAgent.indexOf('Blackberry')!=-1 || navigator.userAgent.indexOf('BlackBerry')!=-1)
    {
    	isBlackBerry = true;
    	window.onload = 'callback_function()';
    }
    else
    {
    	script.onload = callback_function; //execute
    }
}
html_doc.appendChild(script);


//Function for Safari iFrame 3rd party cookies workaround
function submitSessionForm() {
	if (firstTimeSession == 0) {
		firstTimeSession = 1;
		jQuery("#wodsessionform").submit();
		setTimeout(emptyFunction(),2000);
	}
}

function emptyFunction(){
	var x=0;
	//this is a placeholder method that just needs to be executed
}

function callback_function() {
	
	//10/1/11 - Adding noConflict call due to the jQuery conflicitng with MooTools. Found
	//when deploying CF Barrington (Forging Elite Websites)
	jQuery.noConflict();
	
	if(!isBlackBerry)
	{	
	  jQuery.getScript(BASE_DOMAIN+"js/jquery-ui-1.8.14.custom.min.js", function(){   		
		  if(navigator.userAgent.indexOf('iPhone')!=-1)
		  {
			   isIPhone = true;
		  }
		  else
		  {
			  //this is a desktop web browser or a tablet. Check for safari.
			  var isSafari = (/Safari/.test(navigator.userAgent));
			  
			  if (isSafari) {
				  jQuery("body").append('<iframe id="wodsessionframe" name="wodsessionframe" onload="submitSessionForm()" src="http://app.wodhopper.com/resources/index.html" style="display:none;"></iframe><form id="wodsessionform" enctype="application/x-www-form-urlencoded" action="http://app.wodhopper.com/api/empty" target="wodsessionframe" method="post"></form>');
			  } //This is the iFrame 3rd Party cookies in Safari workaround. Reference http://anantgarg.com/2010/02/18/cross-domain-cookies-in-safari/
			  
			  jQuery('<div id="wodhopper_modal_dialog_div" style="width:650px;height:520px;"><iframe id="wodhopper_modal_dialog_iframe" src=' + rootTabsUrl + ' width="635px" height="520px" scrolling="no" frameborder="0" style="border:none; overflow:auto;" allowTransparency="true"></iframe></div>').appendTo(document.body);
			  wodhopper_window = jQuery("#wodhopper_modal_dialog_div").dialog({
				   autoOpen:false,
				   width:650,
				   height:565,
				   title:'WODHOPPER: Track Results Not Excuses' //<img src="../css/images/wodhopper_logo.jpg"></img> 
			   });
		  }
		  //append the two links for the floating Divs to the end of the HTML body
		  jQuery('<a title="RSVP to class" id="wodhopper-coming-badge"><span>Coming?</span></a>').appendTo(document.body);
		  jQuery('<a title="See RSVP list" id="wodhopper-menu-badge"><span>WODHOPPER</span></a>').appendTo(document.body);
		  
		  //android browser bug fix for the CSS positioning of the badges.
		  //found especially on the 847 blog.
		  if(/Android/.test(navigator.userAgent) || /android/.test(navigator.userAgent))
		  {
		  		jQuery("#wodhopper-coming-badge").css('position','absolute');
		  		jQuery("#wodhopper-menu-badge").css('position','absolute');
		  }
		  
		  
		  //bug fix for the overlapping of the badge on the anaerobic site.
		  if(/Android/.test(navigator.userAgent) || /android/.test(navigator.userAgent) || isIPhone)
		  {
		  		jQuery("#wodhopper-coming-badge").css('margin-left','-35px');
		  		jQuery("#wodhopper-menu-badge").css('margin-left','-35px');
		  }
		  
		  
		  jQuery('#wodhopper-coming-badge').click(function(){
			  if(isIPhone)
			  {
				  openIPhoneDialog();
			  }
			  else if (isBlackBerry || isOtherMobile)
			  {
				  openMobileSite();
			  }
			  else
			  {
				  openModalDialog(imComingTab);
				  jQuery.postMessage(
					'imComingTab',
					/*
					BUG FIX: 2/21/12 - The hashtag communication needs the rootURL not just the 
					base domain. This was found in case 384 with IE7.
					XSS_BASE_DOMAIN changed to rootTabsUrl
					*/
					rootTabsUrl,
					jQuery("#wodhopper_modal_dialog_iframe").get(0).contentWindow
				  );
			  }
		  });
		  jQuery('#wodhopper-menu-badge').click(function(){
			  if(isIPhone)
			  {
				  openIPhoneDialog();
			  }
			  else if (isBlackBerry || isOtherMobile)
			  {
				  openMobileSite();
			  }
			  else
			  {
				  openModalDialog(whosComingTab);
				  jQuery.postMessage(
					'whosComingTab',
					rootTabsUrl,
					jQuery("#wodhopper_modal_dialog_iframe").get(0).contentWindow
				  );
			  }
		  });		  
 		});
 	 }
 	 else
 	 {
		 var newLink = document.createElement("a");
		 newLink.setAttribute("title","RSVP to class");
		 newLink.setAttribute("id","wodhopper-coming-badge");			
		 newLink.setAttribute("onclick","openMobileSite();");			
		 var newSpan = document.createElement("span");
		 var spanText = document.createTextNode("Coming?");
		 newSpan.appendChild(spanText);
		 newLink.appendChild(newSpan);
		 document.body.appendChild(newLink);
		 
		 document.getElementById("wodhopper-coming-badge").style.background = 'url("http://app.wodhopper.com/css/images/coming_847.png") no-repeat';
		 document.getElementById("wodhopper-coming-badge").style.width = '62px';
		 document.getElementById("wodhopper-coming-badge").style.height = '124px';
		 document.getElementById("wodhopper-coming-badge").style.marginLeft = '-25px';
		 document.getElementById("wodhopper-coming-badge").style.cssFloat = 'left';
		 document.getElementById("wodhopper-coming-badge").style.left = '0px';
		 document.getElementById("wodhopper-coming-badge").style.position = 'fixed';
		 document.getElementById("wodhopper-coming-badge").style.top = '25%';
		 document.getElementById("wodhopper-coming-badge").style.textIndent = '-1000px';
		 document.getElementById("wodhopper-coming-badge").style.zIndex = '999';
		 
		 //Menu Badge
		 var newLink2 = document.createElement("a");
		 newLink2.setAttribute("title","See RSVP List");
		 newLink2.setAttribute("id","wodhopper-menu-badge");
		 newLink2.setAttribute("onclick","openMobileSite();");
		 var newSpan2 = document.createElement("span");
		 var spanText2 = document.createTextNode("WODHOPPER");
		 newSpan2.appendChild(spanText2);
		 newLink2.appendChild(newSpan2);
		 document.body.appendChild(newLink2);
		 
		 document.getElementById("wodhopper-menu-badge").style.background = 'url("http://app.wodhopper.com/css/images/menu_black.png") no-repeat';
		 document.getElementById("wodhopper-menu-badge").style.width = '62px';
		 document.getElementById("wodhopper-menu-badge").style.height = '54px';
		 document.getElementById("wodhopper-menu-badge").style.marginLeft = '-25px';
		 document.getElementById("wodhopper-menu-badge").style.marginTop = '120px';
		 document.getElementById("wodhopper-menu-badge").style.cssFloat = 'left';
		 document.getElementById("wodhopper-menu-badge").style.left = '0px';
		 document.getElementById("wodhopper-menu-badge").style.position = 'fixed';
		 document.getElementById("wodhopper-menu-badge").style.top = '25%';
		 document.getElementById("wodhopper-menu-badge").style.textIndent = '-1000px';
		 document.getElementById("wodhopper-menu-badge").style.zIndex = '999';
 	 }
	
 	//now add the XSS JQueryplugin
 	script2.type = "text/javascript";
	script2.src = BASE_DOMAIN+'js/jquery-postMessage.js';
	//IE:
	if(window.attachEvent && document.all) {
		script2.onreadystatechange = function () {
			if(this.readyState === "complete" || this.readyState === "loaded") {
				callback_function2(); //execute
			}
		};
	}
	//other browsers:
	else {
		script2.onload = callback_function2; //execute
	}
	html_doc.appendChild(script2);
}

function decodeString(raw) {
	var clean = raw;
	
	//replace the '+' with spaces and the %0A%0A with linebreaks
	clean = clean.replace(/\+/gi,' ');
	clean = clean.replace(/%0A/gi,'\n');
	clean = clean.replace(/%09/gi,'\t');
	
	//now convert the chars to be in the URL
	clean = clean.replace(/%3A/gi,':');
	clean = clean.replace(/%2F/gi,'/');
	clean = clean.replace(/%3F/gi,'?');
	clean = clean.replace(/%3D/gi,'=');
	clean = clean.replace(/%40/gi,'@');
	clean = clean.replace(/%23/gi,'#');
	clean = clean.replace(/%24/gi,'$');
	clean = clean.replace(/%25/gi,'%');
	clean = clean.replace(/%5E/gi,'^');
	clean = clean.replace(/%26/gi,'&');
	clean = clean.replace(/%2B/gi,'+');
	clean = clean.replace(/%5B/gi,'[');
	clean = clean.replace(/%7B/gi,'{');
	clean = clean.replace(/%5D/gi,']');
	clean = clean.replace(/%7D/gi,'}');
	clean = clean.replace(/%3B/gi,';');
	clean = clean.replace(/%22/gi,'"');
	clean = clean.replace(/%2C/gi,',');
	clean = clean.replace(/%3C/gi,'<');
	clean = clean.replace(/%3E/gi,'>');
	clean = clean.replace(/%5C/gi,'\\');
	clean = clean.replace(/%7C/gi,'|');
	clean = clean.replace(/%7E/gi,'~');
	clean = clean.replace(/%85/gi,'...');
	
	
	return clean;
}

function callback_function2(){
	//this is where we can setup the loading of XSS items. XSS is now loaded.
	//This is the XSS receive function. This is called from the child
	jQuery.receiveMessage(
		  function(passedObject){
		  	
		  	if(passedObject.data.indexOf('getCookie') != -1)
		  	{
		  		var topSiteCookie = "";
		  		var topSiteCookies = document.cookie.split(';');
		  		var i=0;
		  		for (i=0;i<topSiteCookies.length;i++)
		  		{
		  			if(topSiteCookies[i].indexOf("wh_Name") != -1)
		  			{
		  				topSiteCookie = unescape(topSiteCookies[i].split("=")[1]);
		  			}
		  		}
		  		
		  		jQuery.postMessage(
				  'cookie='+topSiteCookie,
				  XSS_BASE_DOMAIN,
				  jQuery("#wodhopper_modal_dialog_iframe").get(0).contentWindow
				);
		  	}
		  	else if(passedObject.data.indexOf('setCookie') != -1)
		  	{
		  		var cookieToSave = passedObject.data.split("=")[1]+"="+passedObject.data.split("=")[2]+"="+passedObject.data.split("=")[3];
		  		document.cookie = cookieToSave;
		  		
		  		jQuery.postMessage(
				  'cookie='+cookieToSave,
				  XSS_BASE_DOMAIN,
				  jQuery("#wodhopper_modal_dialog_iframe").get(0).contentWindow
				);
		  	}
		  	else if(passedObject.data.indexOf('redirect') != -1)
		  	{
		  		var redirectURL = passedObject.data.split("=")[1];
		  		window.location = redirectURL;
		  	}
		  	else
		  	{	  
			   //unmarshall the object
			   var commentObjectArray = passedObject.data.split("&");
			   var comment = passedObject[0].split("=")[1];
			   comment = decodeString(comment);
			   
			   var author = commentObjectArray[1].split("=")[1];
			   author = decodeString(author);
			   
			   var rssUrl = commentObjectArray[2].split("=")[1];
			   rssUrl = decodeString(rssUrl);
			   
			   
			   var commentPostUrl = commentObjectArray[3].split("=")[1];
			   commentPostUrl = decodeString(commentPostUrl);
			   
			   var commentPostId = -1;
			   
			   //now call the AJAX to parse the sites RSS.
			   jQuery.ajax({
				   type: "GET",
				   url: rssUrl,
				   dataType: "xml",
				   success: function(xml) {
					   //Bug Fix - 7/1/11 - Version 1.5.2
					   //Bug - Previously was a for each loop and would post a comment to each
					   //of the displaying WODs. Instead only post to the most recent WOD.
					   
					   //TODO: This is also not safe b/c the most recent WOD cannot be an event or else
					   //the comment will go to the events page. This can be resolved by using a JSON
					   //entry for the box to set the 'tag' category for the WODs section. An example
					   //of this is for CF847 their category for WODs is "Workout of the Day"
					   
					   
					   /*
						   This is the for each section...will need this soon once we account for 
						   the categories in the posting.
					   
					   jQuery(xml).find('item').each(function(){
						   var rawGuid = jQuery(this).find("guid")[0].textContent;
						   
						   //checking for a WordPress Blog
						   wordpressIndex = rawGuid.indexOf('/?p=');
						   if(wordpressIndex != -1)
						   {
							   //wordpress blog. Get the value of the 'p' parameter which is the ID for the most recent blog to post comment to.
							   commentPostId = rawGuid.substring(wordpressIndex + 4);
							   //now post to the comment blog using JSON Post.
							   var authorString = author;
							   var emailString = "rsvp@wodhopper.com";
							   var urlString = "";
							   var commentString = comment;
							   var commentParentString = 0;
							   
							   //vars that need to be altered after testing
							   var postCommentsUrl = commentPostUrl;
							   var commentPostIdString = commentPostId;
							   
										   
							   //now use jQuery post method to post the comment
							   jQuery.post(postCommentsUrl,
								   { author: authorString, email: emailString, url: urlString, comment: commentString, comment_parent: commentParentString, comment_post_ID: commentPostIdString }, 
								   function(data)
								   {
									   //alert("Successfully posted your comment to the WOD comments section too!");
								   }
							   );
							   
						   }
					   });
					   */
					   
					   
					   var mostRecentPost = jQuery(xml).find('item')[0];
					   
					   //Bug fix for Internet Explorer. TextContent does not exist. must use text 7/5/11
					   var rawGuid = jQuery(jQuery(jQuery(mostRecentPost)[0]).find('guid')[0]).text();
						   
					   //checking for a WordPress Blog
					   wordpressIndex = rawGuid.indexOf('/?p=');
					   if(wordpressIndex != -1)
					   {
						   //wordpress blog. Get the value of the 'p' parameter which is the ID for the most recent blog to post comment to.
						   commentPostId = rawGuid.substring(wordpressIndex + 4);
						   //now post to the comment blog using JSON Post.
						   var authorString = author;
						   var emailString = "rsvp@wodhopper.com";
						   var urlString = "";
						   var commentString = comment;
						   var commentParentString = 0;
						   
						   //vars that need to be altered after testing
						   var postCommentsUrl = commentPostUrl;
						   var commentPostIdString = commentPostId;
									   
						   //now use jQuery post method to post the comment
						   jQuery.post(postCommentsUrl,
							   { author: authorString, email: emailString, url: urlString, comment: commentString, comment_parent: commentParentString, comment_post_ID: commentPostIdString }, 
							   function(data)
							   {
								   //post complete
							   }
						   );
					   }
				   }
			   });
			}
		  },
		  XSS_BASE_DOMAIN
	);
}

function getIsOtherMobile() {
	var ua = navigator.userAgent;
	
	//check for Android Phones
	if(ua.indexOf("Android") != -1)
	{
		return true;
	}
	
	//check for IEMobile Phones
	if(ua.indexOf("IEMobile") != -1)
	{
		return true;
	}
	
	//check for Opera Phones
	if(ua.indexOf("Opera Mini") != -1 || ua.indexOf("Opera Mobi") != -1)
	{
		return true;
	}
	
	//check for Fennec Phones (Mobile Firefox)
	if(ua.indexOf("Fennec") != -1)
	{
		return true;
	}
	
	return false;
}

function openIPhoneDialog(){
	var finalParam = ROOT_TAB_PARAMS;
	var splitParam = ROOT_TAB_PARAMS.split('//');
	var splitParam1 = splitParam[1].split('.');
	if(splitParam1.length == 1 || splitParam1.length == 2)
	{
		//this is an example of http://crossfitXXX.com
		finalParam = "xd="+splitParam1[0];
	}
	else if(splitParam1.length == 3)
	{
		//this is an example of http://www.crossfitXXX.com
		finalParam = "xd="+splitParam1[1];
	}
	
	var rsvpUrl = iOSMobileUrl + "?" + finalParam;
	window.open(rsvpUrl,'RSVP');
}

function openMobileSite(){
	var finalParam = ROOT_TAB_PARAMS;
	var splitParam = ROOT_TAB_PARAMS.split('//');
	var splitParam1 = splitParam[1].split('.');
	if(splitParam1.length == 1 || splitParam1.length == 2)
	{
		//this is an example of http://crossfitXXX.com
		finalParam = "xd="+splitParam1[0];
	}
	else if(splitParam1.length == 3)
	{
		//this is an example of http://www.crossfitXXX.com
		finalParam = "xd="+splitParam1[1];
	}
	
	var rsvpUrl = webMobileUrl + "?" + finalParam;
	window.open(rsvpUrl,'RSVP');
}

function openModalDialog() {
		
	//at this point switch the visible tab
	wodhopper_window.dialog('open');
	return false;
}
