function calculate_time_zone() {
	var rightNow = new Date();
	var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
	var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	temp = june1.toGMTString();
	var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
	var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
	var dst;
	if (std_time_offset == daylight_time_offset) {
		dst = "0"; // daylight savings time is NOT observed
	} else {
		// positive is southern, negative is northern hemisphere
		var hemisphere = std_time_offset - daylight_time_offset;
		if (hemisphere >= 0)
			std_time_offset = daylight_time_offset;
		dst = "1"; // daylight savings time is observed
	}
	//var i;
	 return convert(std_time_offset)+","+dst;
	// check just to avoid error messages
	/*	if (document.getElementById('timezone')) {
		for (i = 0; i < document.getElementById('timezone').options.length; i++) {
		//	if (document.getElementById('timezone').options[i].value == convert(std_time_offset)+","+dst) {
		//		document.getElementById('timezone').selectedIndex = i;
		//		break;
			}
		}
	} */
}

function convert(value) {
	var hours = parseInt(value);
   	value -= parseInt(value);
	value *= 60;
	var mins = parseInt(value);
   	value -= parseInt(value);
	value *= 60;
	var secs = parseInt(value);
	var display_hours = hours;
	// handle GMT case (00:00)
	if (hours == 0) {
		display_hours = "00";
	} else if (hours > 0) {
		// add a plus sign and perhaps an extra 0
		display_hours = (hours < 10) ? "+0"+hours : "+"+hours;
	} else {
		// add an extra 0 if needed 
		display_hours = (hours > -10) ? "-0"+Math.abs(hours) : hours;
	}
	
	mins = (mins < 10) ? "0"+mins : mins;
	return display_hours+":"+mins;
}

onload = calculate_time_zone;


function AddInvitationRow() {
    var firstnamecells = document.getElementsByName('firstnamecount');
    var invitationcount = firstnamecells.length;
    var newindex = invitationcount + 1;
    var newrow = invitationcount * 3 - 1;

    var table = document.getElementById('invitationtable');

    var firstnewrow = table.insertRow(newrow);
    var secondnewrow = table.insertRow(newrow + 1);
    var thirdnewrow = table.insertRow(newrow + 2);

    var firstnewrowfirstcell = firstnewrow.insertCell(0);
    firstnewrowfirstcell.colSpan = "2";
    firstnewrowfirstcell.innerHTML = "<hr class='referafriendhr' name='firstnamecount'>";

    var secondnewrowfirstcell = secondnewrow.insertCell(0);
    secondnewrowfirstcell.innerHTML = "First Name:";
    secondnewrowfirstcell.name = "firstnamecell";
    var secondnewrowsecondcell = secondnewrow.insertCell(1);
    secondnewrowsecondcell.innerHTML = "<input name='FirstName" + newindex + "' style='width:250px'>";

    var thirdnewrowfirstcell = thirdnewrow.insertCell(0);
    thirdnewrowfirstcell.innerHTML = "Email:";
    var thirdnewrowsecondcell = thirdnewrow.insertCell(1);
    thirdnewrowsecondcell.innerHTML = "<input name='Email" + newindex + "' style='width:250px'>";
}

function ReferAFriendFormCheck() {
    var inputs = document.getElementsByTagName('input');

    for(var i=0;i < inputs.length; i++) {
	var input = inputs[i];
	if(input.value && input.name.match(/Email/)) {
	    if(!isEmail(input.value)) {
		alert('Please enter a valid Email address for ' + input.value);
		return false;
	    }
	}
    }

    return true;
}
function SetView(level, total, active, inactive, belowactive, belowinactive, includebelow, ppl) {
    var teamsview = document.getElementById('teamsview');
    var html = '<a href="/dashboard/teams/teamdetail.php?level=' + level + '">View Team Members</a><br>Total Users: ' + total + '<br>Active Members: ' + active + '<br>Inactive Members: ' + inactive;

    if(includebelow) {
	html = html + '<br>Active Members Below: ' + belowactive + '<br>Inactive Members Below: ' + belowinactive;
    }

    teamsview.innerHTML = html;

    var teamsarrow = document.getElementById('teamsarrow');
    var teamarrowpadding = teamsarrow.style.top.substring(0,3) * 1;
    var lastlevel = document.getElementById('CurrentLevel').value;
    var levelnum = level == 'Overall' ? 0 : level;
    if(lastlevel =='Overall') {
	lastlevel=0;
    }
    var leveldiff = levelnum-lastlevel;
    teamsarrow.innerHTML = document.getElementById(level+'_content').innerHTML;
    teamarrowpadding = teamarrowpadding + leveldiff * ppl;
    teamsarrow.style.top = teamarrowpadding + 'px';
    document.getElementById('CurrentLevel').value=level;
}

function TakeASurveyFormCheck() {
    var radiobuttons = document.getElementsByTagName('input');

    var checkarray = new Array();
    for(var i=0;i < radiobuttons.length; i++) {
	var button = radiobuttons[i];

	if(button.checked) {
	    checkarray[button.name] = 2;
	}
	else if(typeof(checkarray[button.name]) == 'undefined') {
	    checkarray[button.name] = 1;
	}
    }

    for(var i=0;i < checkarray.length; i++) {
	if(checkarray[i] == 1) {
	    var buttons = document.getElementsByName(i);
	    alert('Please answer: ' + buttons[0].className);
	    return false;
	}
    }

    return true;
}

function AjaxRequest(location,url,post,callback) {
    var http_request = false;
    
    if (window.XMLHttpRequest) {
	http_request = new XMLHttpRequest();
	if (http_request.overrideMimeType) {
	    http_request.overrideMimeType('text/xml');
	}
    } else if (window.ActiveXObject) {
	try {
	    http_request = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	    try {
		http_request = new ActiveXObject("Microsoft.XMLHTTP");
	    } catch (e) {}
	}
    }
    if (!http_request) {
	alert('Giving up :( Cannot create an XMLHTTP instance');
	return false;
    }

    if(location == 'teamdetailarea') {
	var level = document.getElementById('level');
	var status = document.getElementById('Status');
	var name = document.getElementById('Name');

	post = 'level=' + level.value;

	if(status) {
	    post = post + '&status=' + status.value;
	}
	else if(name) {
	    post = post + '&name=' + name.value;
	}
    }
    else if(location == 'lessonarea') {
	var gurufilter = document.getElementById('GuruFilter');
	var categoryfilter = document.getElementById('CategoryFilter');
	var unwatchedonlyvalue = 0;
	/*var unwatchedonly = document.getElementById('Active');
	var unwatchedonlyvalue = 0;
	if(unwatchedonly.checked) {
	    unwatchedonlyvalue = 1;
	}
	*/
	post = 'GuruFilter=' + gurufilter.value + '&CategoryFilter=' + categoryfilter.value + '&Active=' + unwatchedonlyvalue;
    }
	else if (/*location == 'blogarea' || location == 'gamesarea' ||/* location == 'printarea' ||*/ location == 'surveysarea' || location == 'audioarea') {
		var categoryfilter = document.getElementById('CategoryFilter');
		post = 'CategoryFilter=' + categoryfilter.value + '&Active=1';
	}
	else if (location == 'printarea') {
		var categoryfilter = document.getElementById('CategoryFilter');
		var gurufilter = document.getElementById('GuruFilter');
		
		post = 'CategoryFilter=' + categoryfilter.value + '&GuruFilter=' + gurufilter.value + '&Active=1';
	}
    else if(location == 'storemerchandisearea') {
	var search = document.getElementById('search');  			//search term
	var organizeby = document.getElementById('searchfilter');	//Success Coach
	//var type = document.getElementById('searchfilter2');
	var limit = document.getElementById('limit');

	post = 'Search=' + search.value + '&SearchFilter=' + organizeby.value + /*'&SearchFilter2=' + type.value +*/ '&limit=' + limit.value;
    }
    else if(location == 'storelessonarea') {
	var search = document.getElementById('search');
	var organizeby = document.getElementById('searchfilter');
	var limit = document.getElementById('limit');

	post = 'Search=' + search.value + '&SearchFilter=' + organizeby.value + '&limit=' + limit.value;
    }
    else if(location == 'redemptionarea') {
	var price = document.getElementById('price');
	var name = document.getElementById('name');

	post = post + '&price=' + price.value + '&name=' + name.value;
    }
    else if(location == 'pointsarea') {
		var priceinput = document.getElementById('amount');
		var commis = $("#commission").val();
		//post = post + '&price=' + priceinput.value;
		post = "commission=" + commis + "&price=" + priceinput.value;
		alert(post);
    }
    else if(location == 'messagearea') {
	var filter = document.getElementById('postfilter');
	
	if(filter) {
	    post = post + '&postfilter=' + filter.value;
	}
    }
    //alert(location);
    //alert(post);
    http_request.onreadystatechange = function() {changeStatus(http_request); };
    http_request.open('POST',url, true);
    http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http_request.send(post);
    function changeStatus(http_request) {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
		if(location != null /*&& location != ''*/)
		    document.getElementById(location).innerHTML = http_request.responseText;
		if(location == 'lessonarea' || location == 'blogarea' || location == 'gamesarea' || location == 'printarea' || location == 'surveyarea' || location == 'audioarea') {
		    stripemultiple('stripe');
		}
		else {
		    stripe('stripe');
		}

		//alert(location);
		var regex = /(\d+)itembox/;
		if(location.match(regex)) {
		//	alert('match');
		    AjaxRequest('shoppingcart', '/shop/internalstore/shoppingcartajx.php');
		}
            }
        }

    }
}

function stripe(id) {
    var even = false;
    var evenColor = arguments[1] ? arguments[1] : "#ffffcd";
    var oddColor = arguments[2] ? arguments[2] : "#FFFFFF";
    var table = document.getElementById(id);
    var off  = document.getElementById('noStripe');
    if (! table || off) { return; }
    var tbodies = table.getElementsByTagName("tbody");

    for (var h = 0; h < tbodies.length; h++) {
	var trs = tbodies[h].getElementsByTagName("tr");

	for (var i = 0; i < trs.length; i++) {
	    if (! trs[i].style.backgroundColor) {
		var tds = trs[i].getElementsByTagName("td");

		for (var j = 0; j < tds.length; j++) {
		    var mytd = tds[j];
		    //         if (! mytd.style.backgroundColor) {                                                                                                                                                                
		    mytd.style.backgroundColor = even ? evenColor : oddColor;
		    //         }                                                                                                                                                                                                  
		}
	    }
	    even =  ! even;
	}
    }
}

function stripemultiple(name) {
    var even = false;
    var evenColor = arguments[1] ? arguments[1] : "#ffffcd";
    var oddColor = arguments[2] ? arguments[2] : "#FFFFFF";
    var tables = document.getElementsByName(name);
    var off  = document.getElementById('noStripe');
    if (off) { return; }
    for (var t = 0; t < tables.length; t++) {
	var tbodies = tables[t].getElementsByTagName("tbody");
	even = 0;
	for (var h = 0; h < tbodies.length; h++) {
	    var trs = tbodies[h].getElementsByTagName("tr");

	    for (var i = 0; i < trs.length; i++) {
		if (! trs[i].style.backgroundColor) {
		    var tds = trs[i].getElementsByTagName("td");

		    for (var j = 0; j < tds.length; j++) {
			var mytd = tds[j];
			//         if (! mytd.style.backgroundColor) {                                                                                                                                                                
			mytd.style.backgroundColor = even ? evenColor : oddColor;
			//         }                                                                                                                                                                                                  
		    }
		}
		even =  ! even;
	    }
	}
    }
}

function ChangeFilter() {
    var select = document.getElementById('teamfilter');
    var teamfilterarea = document.getElementById('teamfilterarea');
    var filterbutton = document.getElementById('filterbutton');
    if(!select.value) {
	teamfilterarea.innerHTML = '';
	teamfilterarea.style.paddingTop = '';
	AjaxRequest('teamdetailarea', '/dashboard/teams/teamdetailajx.php');
    }
    else if(select.value == 'Status') {
	teamfilterarea.innerHTML = "<div style='float:left;margin-top:10px;margin-right:15px;'>" + 
	    "Status: <select name='Status' id='Status'><option value='Active'>Active</option><option value='Inactive'>Inactive</option></select></div>" +
	    "<div style='float:left;'>" + filterbutton.innerHTML + "</div><div style='clear:both;'></div>";
	teamfilterarea.style.paddingTop = '5px';
    }
    else if(select.value == 'Name') {
	teamfilterarea.innerHTML = "<div style='float:left;margin-top:10px;margin-right:15px;'>" + 
            "Name: <input name='Name' id='Name'></div>" + 
	    "<div style='float:left;'>" + filterbutton.innerHTML + "</div><div style='clear:both;'></div>";
	teamfilterarea.style.paddingTop = '5px';
    }
}

function FillBillingInfo() {
    if(document.getElementById('samebilling')) {
        var checked = document.getElementById('samebilling').checked;
    }

    if(checked) {
        document.field[0].cardnumber.value = document.getElementById('saved_cardnumber').value;
        document.field[0].cardnumber.disabled = true;

        document.field[0].nameoncard.value = document.getElementById('saved_nameoncard').value;
        document.field[0].nameoncard.disabled = true;

        document.field[0].expirationdatemonth.value = 'MM';
        document.field[0].expirationdatemonth.disabled = true;

        document.field[0].expirationdateyear.value = 'YYYY';
        document.field[0].expirationdateyear.disabled = true;

        document.field[0].cardcode.value = '';
        document.field[0].cardcode.disabled = true;

        document.field[0].address.value = document.getElementById('saved_address').value;
        document.field[0].address.disabled = true;

        document.field[0].city.value = document.getElementById('saved_city').value;
        document.field[0].city.disabled = true;

        document.field[0].state.value = document.getElementById('saved_state').value;
        document.field[0].state.disabled = true;

        document.field[0].zip.value = document.getElementById('saved_zip').value;
        document.field[0].zip.disabled = true;
    }
    else {
        document.field[0].cardnumber.disabled = false;
        document.field[0].cardnumber.value = '';
        document.field[0].nameoncard.disabled = false;
        document.field[0].expirationdatemonth.disabled = false;
        document.field[0].expirationdateyear.disabled = false;
        document.field[0].cardcode.disabled = false;
        document.field[0].address.disabled = false;
        document.field[0].city.disabled = false;
        document.field[0].state.disabled = false;
        document.field[0].zip.disabled = false;
    }
}

function setIframeHeight(iframeName) {
    //var iframeWin = window.frames[iframeName];
    var iframeEl = document.getElementById? document.getElementById(iframeName): document.all? document.all[iframeName]: null;
    if (iframeEl) {
	iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous
	//var docHt = getDocHeight(iframeWin.document);
	// need to add to height to be sure it will all show
	var h = alertSize();
	var new_h = (h-114);
	iframeEl.style.height = new_h + "px";
	//alertSize();
    }
}

function alertSize() {
    var myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
	myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	//IE 6+ in 'standards compliant mode'
	myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	//IE 4 compatible
	myHeight = document.body.clientHeight;
    }
    //window.alert( 'Height = ' + myHeight );
    return myHeight;
}

function CalculatePoints(commission) {
    var pointradioinput = document.getElementById('amount');
    var priceradio = document.getElementById('pointradioprice');
    var skuradio = document.getElementById('pointradiosku');
    if(pointradioinput.value) {
        //placement holder for points calculation
	alert(commission + ' ' + priceinput.value);
	var points = priceinput.value * commission;
	var pointsinput = document.getElementById('points');
	pointsinput.value = points;
    }
}

   function CalcPoints()
   {
	  $.ajax({
		url: "/dashboard/redemption/pointscalc_ajx.php",
		type: "POST",
		data: "Points="+$("#cashvalue").val()+"&advId="+$("#cashratio").val(),
		success: function(data)
		 {
		 	$('#cashcalcvalue').html(data);
		 }
	  });
   }
   

function CalculateRedemptionValue(type, globalpercentage, globalratio, firstlocation, secondlocation) {
    var value = document.getElementById(type + 'value').value;

    if(type == 'cash') {
	var ratio = document.getElementById(type + 'ratio').value;
	var totalcash = value / globalratio;
	var redeemcash = totalcash * globalpercentage;
	var bonuspoints = (value * ratio) - (value * globalpercentage);

	var firstvalue = redeemcash;
	var secondvalue = bonuspoints;
    }
    else if(type == 'points') {
	var ratio = document.getElementById(type + 'ratio').value;
	var totalpoints = value * globalratio;
	var requiredpoints = totalpoints / globalpercentage;
	var bonuspoints = (1 - globalpercentage) * requiredpoints * ratio;

	var firstvalue = requiredpoints;
	var secondvalue = bonuspoints;
    }
    else if(type == 'cashonly') {
	var totalcash = value / globalratio;
	var redeemcash = totalcash * globalpercentage;

	var firstvalue = redeemcash;
    }
    
    var firstelement = document.getElementById(firstlocation);
    var secondelement = document.getElementById(secondlocation);

    if(firstelement) {
	firstelement.innerHTML = (Math.floor(firstvalue * 100)/100);
    }

    if(secondelement) {
	secondelement.innerHTML = Math.floor(secondvalue);
    }
}

function CalculatePointstoCash(points, commission) {
    return floor(points / commission);
}

function CalculateCashtoPoints(cash, commission) {
    return floor(cash * commission);
}

function CalcCashToPointsShop() {
	$.ajax({
		url: "/shop/pointcheckajx.php",
		type: "POST",
		data: "price="+$("#cashvalue").val()+"&id="+$("#ad_id").val(),
		success: function(data)
		 {
		 	$('#pointsarea').html(data);
		 }
	});
}

function CheckPoints(points) {
    var pointsinput = document.getElementById('points');

    if(isNaN(pointsinput.value)) {
	alert('That is not a valid number.');
	return false;
    }
    else if(pointsinput.value > points) {
	alert('You do not have that many points to redeem.');
	return false;
    }
    else {
	return true;
    }
}

function OpenPopup(url, name) {
    window.open(url , name, 'height=250,width=900');
}

function StorePopup(url, id) {
    window.open(url);
    OpenPopup('/shop/storepopup.php?id=' + id, 'Store Information');
}

function StartLessonTimeout(lessonid, viewingid) {
    setTimeout("CheckLesson(" + lessonid + "," + viewingid + ");",5000);
}

function CheckLesson(lessonid, viewingid){
    AjaxRequest('output', '/dashboard/activities/lessons/watchlessonajx.php', 'LessonID=' + lessonid + '&ViewingID=' + viewingid);
    setTimeout("CheckLesson(" + lessonid + "," + viewingid + ");",5000);
}

/////////////////////////////////////////////////////////////////////////////////

function StartAudioTimeout(audioid, viewingid) {
    setTimeout("CheckAudio(" + audioid + "," + viewingid + ");",5000);
}

function CheckAudio(audioid, viewingid){
    AjaxRequest('output', '/dashboard/activities/audio/listenaudioajx.php', 'AudioID=' + audioid + '&ViewingID=' + viewingid);
    setTimeout("CheckAudio(" + audioid + "," + viewingid + ");",5000);
}

function ChangeLevel() {
    var select = document.getElementById('changelevel');
    var level = select.value;

    window.location = '/dashboard/teams/teamdetail.php?level=' + level;
}

function startCountdown(lim, id) {
	setTimeout("displaySurvey("+id+")",lim * 1000);
	countDown(lim); 
}

function countDown(lim) {
	if(lim > 0) {
		$("#timer").html(--lim);
		t = setTimeout("countDown("+lim+")",1000);
	}
	else {
		clearTimeout(t);
		
	}
}

function showSurveyButton(id) {
	$("#survey_button").show();
	$("#timerwrapper").hide();
}

function displaySurvey(id) {
	$("#survey_button").show();
	$("#timerwrapper").hide();
	$.ajax({
		type: "POST",
		url: "/dashboard/activities/print/takeasurveyajx.php",
		data: "printid="+id,
		success: function(msg){
			$("#surveybutton").hide();
			$("#articlesurveyarea").html(msg);
		}
	});
}

function displaySurveyForVideo(id) {
	$.ajax({
		type: "POST",
		url: "/dashboard/activities/print/takeasurveyajx.php",
		data: "LessonID="+id+"&Type=Video",
		success: function(msg){
			$("#surveybutton").html(msg);
			
		//	$("#lessonsurveyarea")
		}
	});
}

function displaySurveyForAudio(id) {
	$.ajax({
		type: "POST",
		url: "/dashboard/activities/print/takeasurveyajx.php",
		data: "idAudio="+id+"&Type=Audio",
		success: function(msg){
			$("#surveybutton").html(msg);
			//$("#audiosurveyarea")
		}
	});
}

function displaySurveyForVideoPaid(id,getid,getcatid,getpaidid) {
	$.ajax({
		type: "POST",
		url: "/dashboard/activities/print/takeasurveyajx.php",
		data: "LessonID="+id+"&Type=Video"+"&getid="+getid+"&getcatid="+getcatid+"&getpaidid="+getpaidid,
		success: function(msg){
			$("#surveybutton").html(msg);
			
		//	$("#lessonsurveyarea")
		}
	});
}

function displaySurveyForAudioPaid(id,getid,getcatid,getpaidid) {
	$.ajax({
		type: "POST",
		url: "/dashboard/activities/print/takeasurveyajx.php",
		data: "idAudio="+id+"&Type=Audio"+"&getid="+getid+"&getcatid="+getcatid+"&getpaidid="+getpaidid,
		success: function(msg){
			$("#surveybutton").html(msg);
			//$("#audiosurveyarea")
		}
	});
}

//var commenthtml = "<textarea name='blogcomment' id='blogcomment' rows='6' cols='50' style='margin-left: 10px'></textarea>";

function addComment(uid) {
	$("#com").removeAttr("onclick");
	$("#commentsarea").fadeIn();
	$("#nocomments").hide();
	$("#commentheader").show();
	$("#commentheader").html("Add a Comment:");
	
	$("#new_comment").fadeIn();
	/*$.ajax({
		type: "POST",
		url: "/GetUserAvatarajx.php",
		data: "uid="+uid,
		success: function(my_avatar){
			//$("#commentsareatable").prepend("<tr id='new_comment'><td id='my_avatar' class='dashed_bottom'>" + my_avatar + "</td><td class='dashed_bottom'>" + commenthtml + "</td><td class='dashed_bottom'><button onclick='submitComment("+uid+")'>Submit Comment</button></td></tr>");
			
		}
	});*/
}

function seeComments(uid) {
	$("#commentheader").show();
	$(".hidden").fadeIn();
	$("#commentsarea").fadeIn();
}

function submitComment(uid) {
	var comment_body = $("#blogcomment").val();
	var my_avatar = $("#my_avatar").html();

/*	if($("#NetworkPublishComment:checked").val())
	{
		RPXNOW.loadAndRun(['Social'], function () {
			var activity = new RPXNOW.Social.Activity(
			comment_body,
			"commented on " + $("#NetworkShareActivity").val() + " on successimo.com",
			"http://www.successimo.com/landingpage.php");
			RPXNOW.Social.publishActivity(activity);	
		});
	}
	*/
	$.ajax({
		type: "POST",
		url: "/dashboard/activities/blogs/commentajx.php",
		data: 
			{
				commentbody:comment_body,
				blogid:blog_id,
				uid:uid,
				type:blog_type,
				title:$("#NetworkShareActivity").val(),
				SocialNetwork: $("#NetworkPublishComment:checked").val()
			},
		success: function(comm) {
			$("#new_comment").hide();			
			$("#commentsareatable").prepend(comm);
			$("#commentsarea").prepend("<h2 style='font-size:14px;margin-top:7px;'>Thank you, your comment has been submitted.</h2>");
			$("#commentheader").html("Comments:");
			seeComments();
		}
	});
}

function deleteComment(commid) {
	if(confirm("Are you sure you want to delete this comment? \nThis action cannot be undone.")) {
		$.ajax({
			type: "POST",
			url: "/dashboard/activities/blogs/commentajx.php",
			data: "commentid="+commid+"&delete=1",
			success: function(comm) {
				$(".comment_"+commid).fadeOut();
			}
		});
	}
}

function agree(commid) {
	$.ajax({
		type: "POST",
		url: "/dashboard/activities/blogs/commentajx.php",
		data: "commentid="+commid+"&agree=1",
		success: function(new_num) {
			$("#ag_"+commid).fadeOut("fast");
			$("#ag_"+commid).html(new_num);
			$("#ag_"+commid).fadeIn();
			
			$("#ag_link_"+commid).replaceWith("<span>agree</span>");
			$("#dis_link_"+commid).replaceWith("<span>disagree</span>");
		}
	});
}

function disagree(commid) {
	$.ajax({
		type: "POST",
		url: "/dashboard/activities/blogs/commentajx.php",
		data: "commentid="+commid+"&disagree=1",
		success: function(new_num) {
			$("#dis_"+commid).fadeOut("fast");
			$("#dis_"+commid).html(new_num);
			$("#dis_"+commid).fadeIn();
			
			$("#ag_link_"+commid).replaceWith("<span>agree</span>");
			$("#dis_link_"+commid).replaceWith("<span>disagree</span>");
		}
	});
}

function reportAbuse(commid) {
	if(confirm("Are you sure you want to report this comment? \nThis action cannot be undone.")) {
		$.ajax({
			type: "POST",
			url: "/dashboard/activities/blogs/commentajx.php",
			data: "commentid="+commid+"&report=1",
			success: function(comm) {
				
				//$("#report_"+commid).hide();
				//$("#report_"+commid).removeAttr("onclick");
				$("#report_"+commid).replaceWith("<span id='report_"+commid+"' class='reported'>flagged as abusive or inapropriate</span>");
				//$("#report_"+commid).fadeIn();
				
			}
		});
	}
}
  function confirmDelBlog(bid) {
    if(confirm("Are you sure you want to delete this blog?"))
      window.location = '/dashboard/activities/blogs/deleteblog.php?blogid='+ bid;
  }
  
function addReply(id,linktxt)
{
	var reptxt = id=="0" ? "Add Team Message" : "Add Reply";
	if(linktxt.length > 0)
	{
		reptxt = linktxt;
	}
	if($('#ReplyBox'+id).is(":hidden"))
	{
		$('#ReplyBox'+id).fadeIn("slow");
		$('#ReplyLink'+id).html("Cancel");
	} else  {
		$('#ReplyBox'+id).fadeOut("fast",
			function() {
				$('#ReplyLink'+id).html(reptxt);
			}
		);
	}
}
 

function submitReply(id,social)
{
	
	if($("#AddReplyTxt"+id).val().length > 0 )
	{
		if(social == true)
		{
			RPXNOW.loadAndRun(['Social'], function () {
			var activity = new RPXNOW.Social.Activity(
		   $("#AddReplyTxt"+id).val(),
		   $("#AddReplyTxt"+id).val(),
		   "http://www.successimo.com/landingpage.php");
		RPXNOW.Social.publishActivity(activity);
	  });
		}
		$.ajax({
			url: "/dashboard/comment_ajx.php",
			type: "POST",
			data: $('#ReplyForm'+id).serialize()+"&pid="+id,
			datatype: "html",
			success: function(data)
			{
				if(id ==0)
				{
					$('#messagelist').prepend(data);
					addReply(id,'');
					$('#AddReplyTxt'+id).html("");				
				} else  {
					$('#Responses'+id).append(data);
					addReply(id);
					$('#AddReplyTxt'+id).html("");
				}
			}
		});
	} else  {
		alert("Please enter a message to post");
	}
}  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
/*
 * jQuery Expander plugin
 * Version 0.4  (12/09/2008)
 * @requires jQuery v1.1.1+
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */


(function($) {

  $.fn.expander = function(options) {

    var opts = $.extend({}, $.fn.expander.defaults, options);
    var delayedCollapse;
    return this.each(function() {
      var $this = $(this);
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
     	var cleanedTag, startTags, endTags;	
     	var allText = $this.html();
     	var startText = allText.slice(0, o.slicePoint).replace(/\w+$/,'');
     	startTags = startText.match(/<\w[^>]*>/g);
   	  if (startTags) {startText = allText.slice(0,o.slicePoint + startTags.join('').length).replace(/\w+$/,'');}
   	  
     	if (startText.lastIndexOf('<') > startText.lastIndexOf('>') ) {
     	  startText = startText.slice(0,startText.lastIndexOf('<'));
     	}
     	var endText = allText.slice(startText.length);    	  
     	// create necessary expand/collapse elements if they don't already exist
   	  if (!$('span.details', this).length) {
        // end script if text length isn't long enough.
       	if ( endText.replace(/\s+$/,'').split(' ').length < o.widow ) { return; }
       	// otherwise, continue...    
       	if (endText.indexOf('</') > -1) {
         	endTags = endText.match(/<(\/)?[^>]*>/g);
          for (var i=0; i < endTags.length; i++) {

            if (endTags[i].indexOf('</') > -1) {
              var startTag, startTagExists = false;
              for (var j=0; j < i; j++) {
                startTag = endTags[j].slice(0, endTags[j].indexOf(' ')).replace(/(\w)$/,'$1>');
                if (startTag == rSlash(endTags[i])) {
                  startTagExists = true;
                }
              }              
              if (!startTagExists) {
                startText = startText + endTags[i];
                var matched = false;
                for (var s=startTags.length - 1; s >= 0; s--) {
                  if (startTags[s].slice(0, startTags[s].indexOf(' ')).replace(/(\w)$/,'$1>') == rSlash(endTags[i]) 
                  && matched == false) {
                    cleanedTag = cleanedTag ? startTags[s] + cleanedTag : startTags[s];
                    matched = true;
                  }
                };
              }
            }
          }

          endText = cleanedTag && cleanedTag + endText || endText;
        }
     	  $this.html([
     		startText,
     		'<span class="read-more">',
     		o.expandPrefix,
       		'<a href="#">',
       		  o.expandText,
       		'</a>',
        '</span>',
     		'<span class="details">',
     		  endText,
     		'</span>'
     		].join('')
     	  );
      }
      var $thisDetails = $('span.details', this),
        $readMore = $('span.read-more', this);
   	  $thisDetails.hide();
 	    $readMore.find('a').click(function() {
 	      $readMore.hide();

 	      if (o.expandEffect === 'show' && !o.expandSpeed) {
          o.beforeExpand($this);
 	        $thisDetails.show();
          o.afterExpand($this);
          delayCollapse(o, $thisDetails);
 	      } else {
          o.beforeExpand($this);
 	        $thisDetails[o.expandEffect](o.expandSpeed, function() {
            $thisDetails.css({zoom: ''});
            o.afterExpand($this);
            delayCollapse(o, $thisDetails);
 	        });
 	      }
        return false;
 	    });
      if (o.userCollapse) {
        $this
        .find('span.details').append('<span class="re-collapse">' + o.userCollapsePrefix + '<a href="#">' + o.userCollapseText + '</a></span>');
        $this.find('span.re-collapse a').click(function() {

          clearTimeout(delayedCollapse);
          var $detailsCollapsed = $(this).parents('span.details');
          reCollapse($detailsCollapsed);
          o.onCollapse($this, true);
          return false;
        });
      }
    });
    function reCollapse(el) {
       el.hide()
        .prev('span.read-more').show();
    }
    function delayCollapse(option, $collapseEl) {
      if (option.collapseTimer) {
        delayedCollapse = setTimeout(function() {  
          reCollapse($collapseEl);
          option.onCollapse($collapseEl.parent(), false);
          },
          option.collapseTimer
        );
      }
    }
    function rSlash(rString) {
      return rString.replace(/\//,'');
    }    
  };
    // plugin defaults
  $.fn.expander.defaults = {
    slicePoint:       100,  // the number of characters at which the contents will be sliced into two parts. 
                            // Note: any tag names in the HTML that appear inside the sliced element before 
                            // the slicePoint will be counted along with the text characters.
    widow:            4,  // a threshold of sorts for whether to initially hide/collapse part of the element's contents. 
                          // If after slicing the contents in two there are fewer words in the second part than 
                          // the value set by widow, we won't bother hiding/collapsing anything.
    expandText:       'read more', // text displayed in a link instead of the hidden part of the element. 
                                      // clicking this will expand/show the hidden/collapsed text
    expandPrefix:     '&hellip; ',
    collapseTimer:    0, // number of milliseconds after text has been expanded at which to collapse the text again
    expandEffect:     'fadeIn',
    expandSpeed:      '',   // speed in milliseconds of the animation effect for expanding the text
    userCollapse:     true, // allow the user to re-collapse the expanded text.
    userCollapseText: '[collapse expanded text]',  // text to use for the link to re-collapse the text
    userCollapsePrefix: ' ',
    beforeExpand: function($thisEl) {},
    afterExpand: function($thisEl) {},
    onCollapse: function($thisEl, byUser) {}
  };
})(jQuery);


function LaunchDiag(ldiv,width)
	{
		$('#'+ldiv).dialog({
			width:width,
			close: function(event, ui)
					{
						$('#'+ldiv).dialog('destroy');
					}
		});
		
	}
  
  
$(document).ready(function() {	

	//select all the a tag with name equal to modal
	$('a[name=modal]').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		
		//Get the A tag
		var id = $(this).attr('href');
		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').fadeIn(500);	
		$('#mask').fadeTo("fast",0.8);	
	
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();
              
		//Set the popup window to center
		$(id).css('top',  winH/2-$(id).height()/2);
		$(id).css('left', winW/2-$(id).width()/2);
	
		//transition effect
		$(id).fadeIn(2000); 
	
	});
	
	//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		
		$('#mask').hide();
		$('.window').hide();
	});		
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});			
});

function ChangeLoginOpt(val)
{
	if(val == "Successimo")
	{
		$('#SuccessLogin').show();
	}
	if(val == "Facebook")
	{
		$('#SuccessLogin').hide();
	}	
}
function SignIn(urlStr)
{
	var loginType = $("input[@name=LoginType]:checked").attr('value');
	setCookie("loginOpt",loginType,100000);	
	if(loginType == "Facebook")
	{
		window.open('https://login.successimo.com/facebook/connect_start?token_url=http%3A%2F%2Fwww.successimo.com%2FapiCallBack_ajx.php&ext_perm=publish_stream,email','loginwindow','width=400,height=400');
	}
	if(	loginType == "Successimo")
	{
		$('#LoginForm').submit();
		/*
		$.ajax({
			url : urlStr,
			type: "POST",
			data : formdata,
			dataType: "json",
			success: function(data)
			{
				if(data != null && data.result == "success")
				{
					window.location.href="/dashboard";
				} else {
					$("#LogInMsg").html("<b><span style='color:#993333'> Incorrect Login. </span></b>");
				}
				
			}
		});
		*/ 
	} 
}

function setCookie(c_name,value,exdays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

 

function ShareActivity(serverName,type,aid,email)
{
		RPXNOW.loadAndRun(['Social'], function () {
			var activity = new RPXNOW.Social.Activity(
			"Share This Successimo Activity",
			" shared "+$("#NetworkShareActivity").val() + " on Successimo",
			"http://"+serverName+"/landingpage.php?aid="+aid+"&type="+type+ "&uid="+email
			
			);
			
			activity.setTitle("Successimo :  " + $("#NetworkShareActivity").val());
			RPXNOW.Social.publishActivity(activity);	
		});	
}


