
function getUserRating(){
	// DWR call to get the rating details (if exists)
	KickAppsBizComponent.getRatedMediaForUser(Ka.Info.MEDIAID,Ka.Info.USERID,Ka.Info.MEDIATYPE,Ka.Info.AFFILIATESITEID,function(ratingObject){
		// create a new star system object
		mediaRatingSystem = new kap_starSystem(ratingObject!==null ? 'view' : 'rate','L',{avg:Math.round(Ka.Info.AVERAGERATING),numRatings:Ka.Info.VOTES});
		// show the rating system
		mediaRatingSystem.show('currentRatingArea');
	});
}

$j(function(){
	//if not logged in
	if(Ka.Info.USERID===''){
		// create a new star system object
		var mediaRatingSystem = new kap_starSystem('view','L',{avg:Math.round(Ka.Info.AVERAGERATING),numRatings:Ka.Info.VOTES});
		// show the rating system
		mediaRatingSystem.show('currentRatingArea');
		
	//if logged in	
	}else{
		// IF A COMMENT WAS TO BE POSTED
		/*
		IF(KA_G_LOGINSOURCE=='COMMENTS')
		{
			// SUBMIT IT
			SENDMESSAGE();
		}
		*/

		// get the user's rating
		getUserRating();
	}
	
	//do regardless of user login
	ka_initTagsText();
	ka_initAdminTagsText();
});

function kap_rateMedia(rating){
	// DWR call to insert the rating
    KickAppsBizComponent.rateMedia(Ka.Info.USERID,Ka.Info.MEDIAID,Ka.Info.MEDIATYPE,rating,Ka.Info.AFFILIATEID,Ka.Info.AFFILIATESITEID);
}


function getAnswer(flag) {
	var favoriteText = "";
	if (flag === true) {
		favoriteText = getRemoveText();
	} else {
		favoriteText = "<a href='javascript:addFavoriteMedia();'>"+Ka.Messages.ADDTOFAV+"</a>";
	}
	DWRUtil.setValue("favoriteArea", favoriteText);
}

function sendMessage() {
	
	var fbConnectCommentElem = $("ka_fb_connect_comment");
	var fbConnectPublishToFB = false;
	if (fbConnectCommentElem != null) {
		fbConnectPublishToFB = fbConnectCommentElem.checked;	
	}
	if (fbConnectPublishToFB == true) {	
		// gotta make sure the user is logged in
		FB.init("6ea0ca792ef51a977a03f8abca4601a5", "http://" + Ka.Info.DOMAINNAME + "/xd_receiver.htm");
		
		FB.ensureInit(function(){
		    FB.Connect.requireSession(function() {
		    	FB.Facebook.get_sessionState().waitUntilReady(function()
	        	{
	        		var mediaType = Ka.Info.MEDIATYPE;
	        		if (mediaType == "AUDIO") {
	        			mediaType = "track"
	        		}
	        		mediaType = mediaType.toLowerCase();
		        	var comment_data = '{"actor":"' + Ka.Info.USERNAME + '","mediaUrl": "' + window.location.href + '","mediaName": "' + Ka.Info.MEDIANAME + '","mediaType": "' + mediaType + '","siteName": "' + Ka.Info.SITENAME + '","images": [{"src": "' + Ka.Info.AUDIOPHOTOSERVERPATH + Ka.Info.MEDIAPATHTOPREVIEW + '","href": "' + window.location.href + '" } ]}';
					FB.Connect.showFeedDialog(57903614814, eval('(' + comment_data + ')'), null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect); 	
	        	}
	        	); 
	        } 
	        );	        
		 });
	}
	
	var text = $("text").value;
	if (text === "") {return;}
	
	DWRUtil.setValue("text", "");
	
	KickAppsBizComponent.addMessage(text, Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, Ka.Info.USERID, 1024, Ka.Info.AFFILIATESITEID, function (bool) {
		if (bool) {
			// if comment contains a flash object or embed refresh the page
			if (text.indexOf('<object') !== -1 || text.indexOf('<embed') !== -1){
				window.location.reload();
				return;
			}
			
			var thisOddEven;
			var comList = "ka_commentList";
			var userPhoto = Ka.Info.AUDIOPHOTOSERVERPATH + Ka.Info.USERPHOTO;
			if ($("ka_noComments")) {
				$j("#ka_noComments").remove();
				thisOddEven = "even";
			} else {
				var lastMessageOdd = $j("#" + comList + " > li:first")[0].className.indexOf("odd") !== -1;
				thisOddEven = (lastMessageOdd) ? "even" : "odd";
			}
			//Replaced with code follwing for internatiolization purpose
			//var toInsert = "<li class=\"" + thisOddEven + "\"><div class=\"ka_bubble\"><blockquote class=\"ka_contentBody\"><a href=\"/service/displayKickPlace.kickAction?u=" + Ka.Info.USERID + "&amp;as=" + Ka.Info.AFFILIATESITEID + "\"> <span style=\"background: rgb(0, 0, 0) url(" + userPhoto + ") no-repeat scroll center;\" class=\"ka_letterboxComment\"/></a><div class=\"ka_bubbleComment\">" + text + "</div></blockquote><cite><a class=\"ka_contributorName\" href=\"/service/displayKickPlace.kickAction?u=" + Ka.Info.USERID + "&amp;as=" + Ka.Info.AFFILIATESITEID + "\">" + Ka.Info.USERNAME + "</a>, <span class=\"ka_commentDate\">0 seconds ago</span> <span>| <span class=\"ka_flag ka_flag_comment\"><a onclick='javascript :ka_displayInappro(\"ka_inappropriateCommentDiv\"); ka_putCommentDetails(\"" + Ka.Info.USERNAME + "\",\"" + text + "\",\"" + Ka.Info.MEDIAID + "\"); ' href=\"JavaScript: ;\">Flag as Inappropriate</a></span></span></cite></div></li>";
			var uName = '<a class="ka_contributorName" href="/service/displayKickPlace.kickAction?u='+Ka.Info.USERID+'&amp;as='+Ka.Info.AFFILIATESITEID+'">'+Ka.Info.USERNAME+'</a>';
			var dateStamp = '<span class="ka_commentDate">'+Ka.Messages.SECONDS.replace('($count)','0')+'</span>';
			var toInsert=
				'<li class="'
					+thisOddEven
					+'"><div class="ka_bubble"><blockquote class="ka_contentBody"><a href="/service/displayKickPlace.kickAction?u='
					+Ka.Info.USERID
					+'&amp;as='
					+Ka.Info.AFFILIATESITEID
					+'"> <span style="background: rgb(0, 0, 0) url('
					+userPhoto
					+') no-repeat scroll center;" class="ka_letterboxComment"/></a><div class="ka_bubbleComment">'
					+((Ka.Info.AUTOAPPROVALCOMMENTS=="false")?Ka.Messages.COMMENTPENDINGAWAITINGAPPROVAL:Ka.Util.wbr(text,10))
					+'</div></blockquote><cite>'
					+Ka.Messages.COMMENTADDEDON.replace('($userName)',uName).replace('($dateStamp)',dateStamp)
					+' | <span class="ka_flag ka_flag_comment"><a onclick=\'javascript :ka_displayInappro("ka_inappropriateCommentDiv"); ka_putCommentDetails("'+Ka.Info.USERNAME+'","'+ Ka.String.addSlashDoubleQuote(text).replace(/'/g,"") +'"); \' href="JavaScript: ;">'+Ka.Messages.INAPPFLAG+'</a></span>'
					+'</cite></div></li>';
			$j("#ka_commentList").prepend($j(toInsert));
			$("text").value = "";
			if ($j("#ka_commentList li").length > 4) {
				$j("#ka_commentList li:gt(4)").remove();
				if ($j("#ka_shoutBoxViewAll").length === 0) {
					$j("<div id=\"ka_shoutBoxViewAll\"><a href=\"/service/displayShoutBox.kickAction?as=" + Ka.Info.AFFILIATESITEID + "&u=" + Ka.Info.USERID + "&mediaId=" + Ka.Info.MEDIAID + "&mediaType=" + Ka.Info.MEDIATYPE + "\">[ "+Ka.Messages.VIEWALLPP+" ]</a></div>").appendTo("#ka_shoutBoxContainer");
				}
				
			}
		} else {
			Ka.popup(Ka.Messages.ajaxError);
		}
	});
}
function MKP_deleteObject(media, id) {
	var uri = "/update/" + media.toLowerCase() + "DeleteConfirm.kickAction?mediaType=" + media.toUpperCase() + "&mediaId=" + id;
	location.href = uri;
}
initClear = false;
function clearField(obj) {
	if (initClear === false) {
		obj.value = "";
		initClear = true;
	}
}
addCommentFlag = false;
function enableAddCommentButton() {
	if (Ka.Info.USERID === "") {
		Ka.popup("form#ka_loginPopup", function () {
			$("username").focus();
		});
	}
	if (!addCommentFlag) {
		addCommentFlag = true;
		var addCommentBtn = $("ka_sendButton");
		addCommentBtn.disabled = "";
		var shoutBoxInput = ka_findObj("text");
		shoutBoxInput.value = "";
	}
}
function addFavoriteMedia() {
	KickAppsBizComponent.addFavoriteMedia(Ka.Info.USERID, Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, Ka.Info.AFFILIATESITEID, function (flag) {
		if (flag === true) {
			$("favoriteArea").innerHTML = "<a href='javascript:removeFavoriteMedia();'>"+Ka.Messages.REMOVEFROMFAV+"</a>";
		}
	});
}
function removeFavoriteMedia() {
	KickAppsBizComponent.deleteFavoriteMedia(Ka.Info.USERID, Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, Ka.Info.AFFILIATESITEID, function (flag) {
		if (flag === true) {
			$("favoriteArea").innerHTML = "<a href='javascript:addFavoriteMedia();'>"+Ka.Messages.ADDTOFAV+"</a>";
		}
	});
}
var descMaxLimit;
if (Ka.Info.MEDIATYPE != "BLOG") {
	descMaxLimit = 100;
} else {
	if (Ka.Info.PATHTOMEDIA !== "") {
		descMaxLimit = 1500;
	} else {
		descMaxLimit = 2000;
	}
}
function ka_replaceText(id, text) {
	obj = ka_findObj(id);
	obj.innerHTML = text;
}
function initUrlInput() {
	obj = ka_findObj("ka_playerTools_URL");
	obj.value = window.location.href;
}
function ka_toggleGigya(thisLink) {
	divWildfirePost = $("ka_WildfirePost");
	if (divWildfirePost) {
		if (divWildfirePost.style.display == "none") {
			$j(thisLink).html(Ka.Messages.GIGGYACANCELPOST);
			if (!$("wfmodule_divWildfirePost")) {
				Wildfire.initPost("53161", "ka_WildfirePost", 400, 160, {UIConfig:"<config><display showEmail=\"false\" showBookmark=\"false\" showCodeBox=\"false\"/><body><background frame-color=\"Transparent\" background-color=\"Transparent\" /></body></config>", defaultContent:"ka_widgetArea"});
			}
			$j(divWildfirePost).show();
			$j("#closeDiv").show();
		} else {
			$j(thisLink).html(Ka.Messages.GIGGYAADDTONET);
			$j(divWildfirePost).hide();
		}
	}
}
function ka_putCommentDetails(commentUserName, commentText){
	$('commentUserName').value = commentUserName;
	$('commentText').value = commentText;
}

//reccomended list
function toggleRecommnededList(link){
	var thisTabPage=link.id.substr(0,link.id.length-6);
	
	//if this is an ajax link
	if(link!==$('ka_playerVideoList_mostRelated_title')){
	
		//if ajax hasn't been called yet
		if($j('#ka_playerVideoList_newMedia > div').html()===''){
			//add preloader image
			$j('#ka_playerVideoList_newMedia > div,#ka_playerVideoList_mostRated > div,#ka_playerVideoList_mostPopular > div').html('<image alt="loading..." src="'+Ka.Info.STATICSERVERIMAGES+'/loading-barber.gif" style="display:block; margin:0 auto;" />');
			
			//get tab contents via ajax
			KickAppsBizComponent.getAllRelatedMediaForPlayPage(Ka.Info.AFFILIATESITEID,Ka.Info.MEDIATYPE,Ka.Info.MEDIAID,function(a){
			    $j('#ka_playerVideoList_newMedia > div,#ka_playerVideoList_mostRated > div,#ka_playerVideoList_mostPopular > div').html('<div class="ka_playerMediaList_table"><ul id="ka_relatedList"></ul></div>');
			    $j.each(a.NEWMEDIALIST,function(i,n){
			     	var kpHref='/service/displayKickPlace.kickAction?u='+n.userId+'&as='+Ka.Info.AFFILIATESITEID+'&b=';
			     	var uploadedByNEWMEDIALIST = "";
			       	if(n.isDisabled === 'true'){
			    		uploadedByNEWMEDIALIST = Ka.Messages.BYAFORMERMEMBER;
			    	}
			    	else{
			    		uploadedByNEWMEDIALIST = Ka.Messages.LATESTBY.replace('($kpHref)',kpHref).replace('($userName)',n.uploadedBy);
			    	}
			       	$j('#ka_playerVideoList_newMedia > div > div > ul').append('<li><a title="'+n['name']+'" href="/_'+n['name'].replace(' ','').replace('_', '').replace('.', '')+'/'+n.entityType.toLowerCase()+'/'+n.id+'/'+Ka.Info.AFFILIATESITEID+'.html?b="><span style="background: rgb(0, 0, 0) url('+Ka.Info.AUDIOPHOTOSERVERPATH+n.pathToPreview100X75+') no-repeat scroll center;" id="ka_letterboxRelated"></span></a><div class="ka_thumbdetails"><a title="'+n['name']+'" href="/_'+n['name'].replace(' ','').replace('_', '').replace('.', '')+'/'+n.entityType.toLowerCase()+'/'+n.id+'/'+Ka.Info.AFFILIATESITEID+'.html?b=">'+Ka.Util.wbr(n.name,7)+'</a><br />'+uploadedByNEWMEDIALIST+'<br/>'+n.formattedDate+'</div></li>');
			    });
				
			    $j.each(a.MOSTRATEDLIST,function(i,n){
			    	var kpHrefRated='/service/displayKickPlace.kickAction?u='+n.userId+'&as='+Ka.Info.AFFILIATESITEID+'&b=';
			    	var uploadedByMOSTRATEDLIST = "";
					if(n.isDisabled === 'true'){
			    		uploadedByMOSTRATEDLIST = Ka.Messages.BYAFORMERMEMBER;
			    	}
			    	else{
			    		uploadedByMOSTRATEDLIST = Ka.Messages.LATESTBY.replace('($kpHref)',kpHrefRated).replace('($userName)',n.uploadedBy);
			    	}
			    
			    	$j('#ka_playerVideoList_mostRated > div > div > ul').append('<li><a title="'+n['name']+'" href="/_'+n['name'].replace(' ','').replace('_', '').replace('.', '')+'/'+n.entityType.toLowerCase()+'/'+n.id+'/'+Ka.Info.AFFILIATESITEID+'.html?b="><span style="background: rgb(0, 0, 0) url('+Ka.Info.AUDIOPHOTOSERVERPATH+n.pathToPreview100X75+') no-repeat scroll center;" id="ka_letterboxRelated"></span></a><div class="ka_thumbdetails"><a title="'+n['name']+'" href="/_'+n['name'].replace(' ','').replace('_', '').replace('.', '')+'/'+n.entityType.toLowerCase()+'/'+n.id+'/'+Ka.Info.AFFILIATESITEID+'.html?b=">'+Ka.Util.wbr(n.name,7)+'</a><br />'+uploadedByMOSTRATEDLIST+'<br/>'+Ka.Messages.MEDIASTARS.replace('($count)',n.averageRating)+'</div></li>');	
			    	//$j('#ka_playerVideoList_mostRated > div > div > ul').append('<li><a title="'+n[2]+'" href="/'+n[2].replace(' ','_')+'/'+n[3].toLowerCase()+'/'+n[0]+'/'+Ka.Info.AFFILIATESITEID+'.html?b="><span style="background: rgb(0, 0, 0) url('+Ka.Info.AUDIOPHOTOSERVERPATH+'/'+(n[7].replace('.jpg','_100X75.jpg'))+') no-repeat scroll center;" id="ka_letterboxRelated"></span></a><div class="ka_thumbdetails"><a href="/'+n[2].replace(' ','_')+'/'+n[3].toLowerCase()+'/'+n[0]+'/'+Ka.Info.AFFILIATESITEID+'.html?b=">'+n[2]+'</a><br />By <a href="/service/displayKickPlace.kickAction?u='+n[1]+'&as='+Ka.Info.AFFILIATESITEID+'&b=">'+n[11]+'</a><br/>'+n[4]+' stars</div></li>');			    	
			    });
				
			    $j.each(a.MOSTPOPULARLIST,function(i,n){
			    	var kpHrefPop='/service/displayKickPlace.kickAction?u='+n.userId+'&as='+Ka.Info.AFFILIATESITEID+'&b=';
			    	var uploadedByMOSTPOPULARLIST = "";
					if(n.isDisabled === 'true'){
					    uploadedByMOSTPOPULARLIST = Ka.Messages.BYAFORMERMEMBER;
			    	}
			    	else{
			    		uploadedByMOSTPOPULARLIST = Ka.Messages.LATESTBY.replace('($kpHref)',kpHrefPop).replace('($userName)',n.uploadedBy);
			    	}
			    	$j('#ka_playerVideoList_mostPopular > div > div > ul').append('<li><a title="'+n['name']+'" href="/_'+n['name'].replace(' ','').replace('_', '').replace('.', '')+'/'+n.entityType.toLowerCase()+'/'+n.id+'/'+Ka.Info.AFFILIATESITEID+'.html?b="><span style="background: rgb(0, 0, 0) url('+Ka.Info.AUDIOPHOTOSERVERPATH+n.pathToPreview100X75+') no-repeat scroll center;" id="ka_letterboxRelated"></span></a><div class="ka_thumbdetails"><a title="'+n['name']+'" href="/_'+n['name'].replace(' ','').replace('_', '').replace('.', '')+'/'+n.entityType.toLowerCase()+'/'+n.id+'/'+Ka.Info.AFFILIATESITEID+'.html?b=">'+Ka.Util.wbr(n.name,7)+'</a><br />'+uploadedByMOSTPOPULARLIST+'<br/>'+Ka.Messages.MEDIAVIEWS.replace('($count)',n.views)+'</div></li>');			
			    	//$j('#ka_playerVideoList_mostPopular > div > div > ul').append('<li><a title="'+n[2]+'" href="/'+n[2].replace(' ','_')+'/'+n[3].toLowerCase()+'/'+n[0]+'/'+Ka.Info.AFFILIATESITEID+'.html?b="><span style="background: rgb(0, 0, 0) url('+Ka.Info.AUDIOPHOTOSERVERPATH+'/'+(n[7].replace('.jpg','_100X75.jpg'))+') no-repeat scroll center;" id="ka_letterboxRelated"></span></a><div class="ka_thumbdetails"><a href="/'+n[2].replace(' ','_')+'/'+n[3].toLowerCase()+'/'+n[0]+'/'+Ka.Info.AFFILIATESITEID+'.html?b=">'+n[2]+'</a><br />By <a href="/service/displayKickPlace.kickAction?u='+n[1]+'&as='+Ka.Info.AFFILIATESITEID+'&b=">'+n[11]+'</a><br/>'+n[8]+' views</div></li>');			
			    });			    
			});
		}
	}

	//adjust tab pages
	$j('#ka_relatedWrap div.ka_related').hide();
	$j('#'+thisTabPage).show();
	
	//adjust tabs
	$j('#ka_relatedTabs > li > a')
		.css({
			'textDecoration':'underline'
		})
		.removeClass('active');
	
	$j(link)
		.css({
			'textDecoration':'none',
			'className':'active'
		})
		.addClass('active');
}


function friendsEmailed(flag) {
	var friendsEmailedText = Ka.Messages.SENT+ '<a href="javascript: ka_displayFriend();">'+Ka.Messages.EMAILTOFRIENDS+'</a>';	
	if (flag === false) {
		friendsEmailedText = '<span class="ka_error">'+Ka.Messages.EMAILFAILED+'</span> <a href="javascript: ka_displayFriend();">'+Ka.Messages.TRYAGAIN+'</a>';
	}
	DWRUtil.setValue("emailArea", friendsEmailedText);
}
function emailToFriends() {
	ka_hideFriend();
	var friendsEmailedText =  Ka.Messages.SENDING;
	DWRUtil.setValue("emailArea", friendsEmailedText);
	KickAppsBizComponent.emailToFriends(DWRUtil.getValue("emailMessage"), DWRUtil.getValue("emailFromName"), DWRUtil.getValue("emailToFriends"), Ka.Info.AFFILIATESITEID, Ka.Info.MEDIANAME, Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, Ka.Info.B, Ka.Info.USERID, friendsEmailed);
	DWRUtil.setValue("emailMessage", "");
	DWRUtil.setValue("emailFromName", "");
	DWRUtil.setValue("emailToFriends", "");
}
function inappropriateMediaflagged(inappropriateflag) {
	if (inappropriateflag === true || Ka.Info.USERID === '') {
		obj = ka_findObj("flagArea");
		if (obj) {
			var flagText =  Ka.Messages.AFTERFLAGGING;
			obj.innerHTML = flagText;
		}
		obj1 = ka_findObj("ka_flagSuccess");
		if (obj1) {
			obj1.innerHTML = Ka.Messages.MEDIAFLAGGINGTHANKSFORHELP.replace('($siteName)',Ka.Info.SITENAME).replace('($siteName)',Ka.Info.SITENAME);
			obj1.style.display = "";
		}
	}
}
function flagInappropriateMedia() {
	KickAppsBizComponent.inAppropriateFlaggingConfirm(Ka.Info.IP, DWRUtil.getValue("flagMsg"), Ka.Info.B, Ka.Info.MEDIANAME, Ka.Info.AFFILIATESITEID, Ka.Info.USERID, Ka.Info.USERID, Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, Ka.Info.MEDIATYPE, inappropriateMediaflagged);
}
// called when a comment is flagged
function inappropriateCommentflagged(bool) {
	//console.log(bool);
	//if (bool){
		//$j(ka_LastCommentFlagged).parent().empty().html('Flagged');
	//}
	// Ka.Messages.MEDIAFLAGGINGTHANKSFORHELP.replace('($siteName)',Ka.Info.SITENAME).replace('($siteName)',Ka.Info.SITENAME);
}
var ka_LastCommentFlagged;
function inAppropriateCommentFlaggingConfirm(thisLink) {
	ka_LastCommentFlagged = thisLink;
	KickAppsBizComponent.inAppropriateCommentFlaggingConfirm(DWRUtil.getValue("commentUserName"), DWRUtil.getValue("commentText"), DWRUtil.getValue("commentFlagMsg"), DWRUtil.getValue("CommentInappropate_B"), Ka.Info.MEDIANAME, DWRUtil.getValue("AffiliateSiteId_CommentInappropate"), DWRUtil.getValue("UserID_CommentInappropate"), Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, inappropriateCommentflagged);
}
var displayInappro = false;
var displayFriend = false;
var onTOS;
var curId = "none";
function ka_toogleInappro(id, display) {
	ka_positionCenter(id);
	obj = ka_findObj(id);
	obj.style.display = display;
}
function ka_displayInappro(id) {
	toggleFlashVideoOff();
	curId = id;
	ka_toogleInappro(id, "block");
	if (displayInappro === false) {
		ka_shadeOn();
	} else {
	}
	displayInappro = true;
}
function ka_updateInappro() {
	if (displayInappro) {
		if (curId == "ka_inappropriateDiv") {
			ka_displayInappro("ka_inappropriateDiv");
		} else {
			ka_displayInappro("ka_inappropriateCommentDiv");
		}
	}
}
ka_addEvent(window, "resize", ka_updateInappro);
ka_addEvent(window, "scroll", ka_updateInappro);
ka_addEvent(window, "resize", ka_updateFriend);
ka_addEvent(window, "scroll", ka_updateFriend);
function ka_hideInappro(id) {
    // if site styler isn't open
    if(!$('ka_le') || ($('ka_le') && Ka.LE.$('ka_le').style.display!=='block')) {
	    toggleFlashVideoOn();
	}
	displayInappro = false;
	ka_toogleInappro(id, "none");
	ka_shadeOff();
}
function ka_updateFriend() {
	if (displayFriend) {
		ka_displayFriend();
	}
}
function ka_toogleFriend(display) {
	id = "ka_emailAFriendDiv";
	ka_positionCenter(id);
	obj = ka_findObj(id);
	obj.style.display = display;
}
function ka_displayFriend() {
	toggleFlashVideoOff();
	ka_toogleFriend("block");
	if (displayFriend === false) {
		ka_shadeOn();
	}
	displayFriend = true;
}
function ka_hideFriend() {
	var inputs = $("ka_emailAFriend").getElementsByTagName("input");
	var textbox = $("emailMsg");
	displayFriend = false;
	ka_toogleFriend("none");
	ka_shadeOff();
    // if site styler isn't open
    if($('ka_le') && Ka.LE.$('ka_le').style.display!=='block') {
	    toggleFlashVideoOn();
	}
}

function setAdminTags() {
	var text_tags = $("ka_playerAddAdminTagsInput").value;
	if (text_tags == Ka.Messages.ADDTAGS) {return;}
	$j("#ka_adminTagError").html("");
	if (text_tags !== "") {
		KickAppsBizComponent.validateTagsForMediaByOtherUsers(text_tags, Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, true, Ka.Info.AFFILIATESITEID, function (error) {
			if (error == null) {
				// no error, save tags.
				KickAppsBizComponent.setAdminTagsForMediaByOtherMembers(
					text_tags, 
					Ka.Info.MEDIAID, 
					Ka.Info.MEDIATYPE, 
					Ka.Info.MEDIAOWNERID, 
					Ka.Info.USERID, 
					Ka.Info.AFFILIATESITEID, 
					Ka.Info.AFFILIATEID, 
					Ka.Info.MEDIANAME, 
					gotAdminTags
				);
				$j("#ka_playerAddAdminTagsInput").val('');
			} else {
				$j("#ka_adminTagError").html(error);
			}
		});
	}
}

function setTags() {
	if (Ka.Info.USERID === "") {
		Ka.popup("#ka_loginPopup");
		return false;
	}
	var text_tags = $("ka_playerAddTagsInput").value;
	if (text_tags == Ka.Messages.ADDTAGS) {return;}
	$j("#ka_tagError").html("");
	if (text_tags !== "") {
		KickAppsBizComponent.validateTagsForMediaByOtherUsers(text_tags, Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, false, Ka.Info.AFFILIATESITEID, function (error) {
			if (error == null) {
				// no error, save tags.
				KickAppsBizComponent.setTagsForMediaByOtherMembers(
					text_tags, 
					Ka.Info.MEDIAID, 
					Ka.Info.MEDIATYPE, 
					Ka.Info.MEDIAOWNERID, 
					Ka.Info.USERID, 
					Ka.Info.AFFILIATESITEID, 
					Ka.Info.AFFILIATEID, 
					Ka.Info.MEDIANAME, 
					gotTags
				);
				$j("#ka_playerAddTagsInput").val('');
			} else {
				$j("#ka_tagError").html(error);
			}
		});
	}
}

function gotTags(tags) {
	var tagLinksText = "";
	for (var j = 0; j < tags.length; j++) {
		var indx=tags[j].indexOf(" ");
		var hrefTag="";
	    if(indx > 0) {
	    	hrefTag = "%22"+tags[j]+"%22";
	    } else {
	    	hrefTag = tags[j];
	    }
		tagLinksText += "<a href=\"/service/searchEverything.kickAction?keywords=" + hrefTag + "&as=" + Ka.Info.AFFILIATESITEID + "\">" + tags[j].toLowerCase() + "</a> ";
	}
	if (tagLinksText !== "") {
		DWRUtil.setValue("ka_tagsText", tagLinksText);
	}
	$("ka_playerAddTagsInput").focus();
	ka_initTagsText();
}

function gotAdminTags(tags){
	var tagLinksText = "";
	for (var j = 0; j < tags.length; j++)
    {
    	var indx=tags[j].indexOf(" ");
		var hrefTag="";
	    if(indx > 0) {
	    	hrefTag = "%22"+tags[j]+"%22";
	    } else {
	    	hrefTag = tags[j];
	    }
    	tagLinksText += '<a href="/service/searchEverything.kickAction?keywords='+hrefTag+
    	'&as='+Ka.Info.AFFILIATESITEID+'">'
    	+tags[j].toLowerCase()+'</a> ';
    }
    
    var obj = ka_findObj("ka_adminTagsText");

     
    if (obj === undefined){return;}
    
    if(tagLinksText !== "")
    {
    	DWRUtil.setValue("ka_adminTagsText", tagLinksText);
    	
    }
    
    $('ka_playerAddAdminTagsInput').focus();
	ka_initAdminTagsText( );
    
}


function checkTags() {
	KickAppsBizComponent.getTagsStringForMediaForAjaxPage(Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, gotTags);
}
function checkAdminTags() {
	KickAppsBizComponent.getAdminTagsStringForMediaForAjaxPage(Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, gotAdminTags);
}
var adminTagsText = "";
var truncAdminTags = "";
var adminTagsLimit = 10000;
function ka_initAdminTagsText() {
	var adminTagsText = "";
	var truncAdminTags = "";
	var adminTagsLimit = 10000;
	adminTagsText = "";
	truncAdminTags = "";
	var obj = ka_findObj("ka_adminTagsText");
	if (ka_findObj("ka_adminTagsText") !== undefined && ka_findObj("ka_adminTagsText") !== null) {
		ka_findObj("ka_adminTagsText").style.display = "inline";
	}
	if (!obj) {
		return;
	}
	adminTagsText = obj.innerHTML;
	var piecesTags = [];
	var words = [];
	re = /<a.*?>(.*?)<\/a> /g;
	splitChars = "> ";
	var tags = adminTagsText.split(splitChars);
	var totalWordCount = 0;
	for (var t = 0; t < tags.length; t++) {
		fb = tags[t].indexOf(">");
		lb = tags[t].lastIndexOf("<");
		word = tags[t].slice(fb + 1, lb);
		if (word.trim() != "") {
			words[words.length] = word;
			totalWordCount += word.length + 1;
			piecesTags[piecesTags.length] = tags[t] + splitChars;
		}
	}
	if (totalWordCount <= 0) {
		return;
	}
	var wordCount = 0;
	for (var w = 0; w < words.length; w++) {
		pieceCount = words[w].length;
		if ((wordCount + pieceCount) < adminTagsLimit) {
			truncAdminTags += piecesTags[w] + " ";
			wordCount += pieceCount + 1;
		}
	}
	if (wordCount > 0) {
		var titleObj = ka_findObj("ka_adminTagsTitle");
		titleObj.style.display = "";
	}
	if (wordCount < totalWordCount) {
		truncAdminTags += "<br />(<a href='javascript: ka_moreAdminTags( );'>"+Ka.Messages.MORE+"</a>)";
		adminTagsText += "<br />(<a href='javascript: ka_lessAdminTags( );'>"+Ka.Messages.LESS+"</a>)";
	}
	obj.innerHTML = truncAdminTags;
}
function ka_moreAdminTags() {
	ka_replaceText("ka_adminTagsText", adminTagsText);
}
function ka_lessAdminTags() {
	ka_replaceText("ka_adminTagsText", truncAdminTags);
}
function ka_initTagsText() {
	var tagsText = "";
	var truncTags = "";
	var tagsLimit = 10000;
	tagsText = "";
	truncTags = "";
	var obj = ka_findObj("ka_tagsText");
	if (ka_findObj("ka_tagsText") != undefined && ka_findObj("ka_tagsText") != null) {
		ka_findObj("ka_tagsText").style.margin = "0";
		ka_findObj("ka_tagsText").style.display = "inline";
	}
	if (!obj) {
		return;
	}
	tagsText = obj.innerHTML;
	piecesTags = [];
	words = [];
	re = /<a.*?>(.*?)<\/a> /g;
	splitChars = "> ";
	tags = tagsText.split(splitChars);
	totalWordCount = 0;
	for (var t = 0; t < tags.length; t++) {
		fb = tags[t].indexOf(">");
		lb = tags[t].lastIndexOf("<");
		word = tags[t].slice(fb + 1, lb);
		if (word.trim() != "") {
			words[words.length] = word;
			totalWordCount += word.length + 1;
			piecesTags[piecesTags.length] = tags[t] + splitChars;
		}
	}
	if (totalWordCount <= 0) {
		return;
	}
	wordCount = 0;
	for (var w = 0; w < words.length; w++) {
		pieceCount = words[w].length;
		if ((wordCount + pieceCount) < tagsLimit) {
			truncTags += piecesTags[w] + " ";
			wordCount += pieceCount + 1;
		}
	}
	if (wordCount > 0) {
		var titleObj = ka_findObj("ka_tagsTitle");
		titleObj.style.display = "";
	}
	if (wordCount < totalWordCount) {
		truncTags += "<br />(<a href='javascript: ka_moreTags( );'>"+Ka.Messages.MORE+"</a>)";
		tagsText += "<br />(<a href='javascript: ka_lessTags( );'>"+Ka.Messages.LESS+"</a>)";
	}
	obj.innerHTML = truncTags;
}
function ka_moreTags() {
	ka_replaceText("ka_tagsText", tagsText);
}
function ka_lessTags() {
	ka_replaceText("ka_tagsText", truncTags);
}

//GIGYA CODE DO NOT MODIFY

if (typeof Wildfire == 'undefined') {
	Wildfire= new Object();
	Wildfire.LinkedLoading = true;
	Wildfire._pixeIframeCreated = false;
} 


Wildfire.Flash={

isIE  : (navigator.appVersion.indexOf("MSIE") != -1) ? true : false,
isWin : (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false,
isOpera : (navigator.userAgent.indexOf("Opera") != -1) ? true : false,

AC_Generateobj:function(objAttrs, params, embedAttrs) { 
	var str = '';
	if (this.isIE && this.isWin && !this.isOpera)	{
		str += '<object ';
		for (var i in objAttrs) {str += i + '="' + objAttrs[i] + '" ';}
		str += '>';
		for (var i in params) {str += '<param name="' + i + '" value="' + params[i] + '" /> ';}
		str += '</object>';
	}
	else {
		str += '<embed ';
		for (var i in embedAttrs) {str += i + '="' + embedAttrs[i] + '" ';}
		str += '> </embed>';
	}
	return str;
},

AC_FL_GetContent:function(){
	var ret = this.AC_GetArgs(arguments);
	return this.AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
},

AC_GetArgs:function(args, classid, mimeType){
	var ret = {};
	ret.embedAttrs = {};
	ret.params = {};
	ret.objAttrs = {};
	for (var i=0; i < args.length; i=i+2){
		var currArg = args[i].toLowerCase();    
		switch (currArg){	
			case "movie":	
				ret.embedAttrs["src"] = args[i+1];
				ret.params["movie"] = args[i+1];
			break;
			case "id":  
			case "width":
			case "height":
			case "align":
			case "name":
				ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
			break;
			default:
				ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
		}
  }
  ret.objAttrs['codebase']='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0';
  ret.objAttrs["classid"] = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000";
  ret.embedAttrs["type"] ="application/x-shockwave-flash";
  ret.embedAttrs['pluginspage']='http://www.macromedia.com/go/getflashplayer';
  
  return ret;
}

} // Wildfire.Flash

// Event handlers
Wildfire.onClose = Wildfire.onPostProfile = Wildfire.onPostComment = Wildfire.onSend = Wildfire.onEmail = function(){};

Wildfire.modules = new Object();
Wildfire.modulesArray = new Array();


/*** PUBLIC METHODS ***/
	
Wildfire.initShare = function(partner, targetId, width, height, config)	{   
	return Wildfire._createJSModule("share",''+partner,targetId,width,height,config,
						'cssURL,cornerRoundness,initialMessageType,domainForCallback,partner,source,partnerData,width,height,emailTabHidden,customCheckboxVisible,customCheckboxChecked,customCheckboxText,' +
						'internalColor,frameColor,externalColor,tabTextColor,textColor,fontType,fontSize,' +
						'headerInternalColor,headerFrameColor'
						);
}

Wildfire.initPost = function(partner, targetId, width, height, config) {	
	return Wildfire._createFlashModule("post",''+partner,targetId,width,height,config);
}



//DEPRECATED, replaced by initShare */
Wildfire.init = Wildfire.initShare;

//DEPRECATED, replaced by module.applyConfig*/
Wildfire.applyConfig= function(config) {
	if (isnotnull(Wildfire.share)) Wildfire.share.applyConfig(config);
}

/*** Flash Interface ***/
//this is Called from the SWF
Wildfire._GetFlashModuleXMLConfig=function (targetId){
	//hide the js progress indicator -- this is a mac issue fix.;
	var pdiv = document.getElementById(targetId+"_progress");
	if (pdiv!=null) {
		pdiv.innerHTML='&nbsp;';
		pdiv.style.display = "none";
		pdiv.style.visibility = "hidden";
	}
	
	xs= ['config',[], [
			'display',['width','height','showCodeBox','rememberMeVisible','emailImportProviders','networksToShow','networksToHide','bookmarksToShow','bookmarksToHide','bulletinChecked','showEmail','showPost','showBookmark','showDesktop', 'showCloseButton'],
			'body',['font=fontType','size=fontSize'],[
				'background',['frame-color=frameColor','background-color=internalColor','corner-roundness=cornerRoundness'],
				'controls',[], [
					'textboxes',[],	[
						'inputs',['color=textInputColor','background-color=textInputBackgroundColor','frame-color=textInputBorderColor']
						],
					'snbuttons',['color=tabTextColor|snButtonsTextColor','background-color=snButtonsBackgroundColor','frame-color=snButtonsFrameColor','over-color=tabTextColor|snButtonsOverTextColor','over-background-color=snButtonsOverBackgroundColor','over-frame-color=snButtonsOverFrameColor'],
					'buttons',['font=fontType|buttonFontType','color=buttonTextColor']
					],
				'texts background-color="transparent" ',['color=textColor'],[
					'messages',['color=messageTextColor'],
					'links',['font=linkFontType','color=linkTextColor'],
					'privacy',['color=privacyTextColor']
					]
				]
			]
		];

	var oConfig=Wildfire._GetFlashModuleConfig(targetId);
	var s=Wildfire._BuildXMLConfigFromJSON(oConfig,xs);
	
	return s;

}

Wildfire._GetFlashModuleConfigAttribute=function (targetId,configAttribute,canBeTextareaID,network){
	//hide the js progress indicator -- this is a mac issue fix.;
	var pdiv = document.getElementById(targetId+"_progress");
	if (pdiv!=null) {
		pdiv.innerHTML='&nbsp;';
		pdiv.style.display = "none";
		pdiv.style.visibility = "hidden";
	}

	var module=Wildfire.modules[targetId];
	if (module!=null) {
		var AttribValue=module.config[configAttribute];
		if (typeof AttribValue=='undefined') return null;
		if (typeof AttribValue=='function') return AttribValue(configAttribute,network);
		if (canBeTextareaID==true) {
			if ( isnotnull(AttribValue) ) {
				try {
					var element=document.getElementById(AttribValue);
					
					if ( isnotnull(element) ) {
						return element.value;
					}
					else {
						return AttribValue;
					}
					
				} catch (e) {
					//GIGYAONLY:alert('Unable to get template for module:' + targetId + ', configAttribute :'+ configAttribute + '\n' + ex.description);
					return AttribValue;	
				}
			}
		}
		else {
			return AttribValue;
		}
	}
	else {
		return {error:'Modlue not found',MID:targetId};
	}
}

Wildfire._GetFlashModuleConfig=function (targetId){
	if (Wildfire.modules == null) {
		alert('Wildfire has no modules yet');
	}
	var module=Wildfire.modules[targetId];
	if (module!=null) {
	
		var res=module.config;
		return res;
	}
	else {
		return null;
	}
}
	

/*** PRIVATE METHODS ***/

Wildfire._BuildXMLConfigFromJSON=function (oConfig,xs) {

	var s=new Array();
	try{
	for(var i=0;i<xs.length;i+=2){

		s[s.length]='<'+xs[i]+' ';
		var atts=xs[i+1];

		for (var ia=0;ia<atts.length;ia++) {
		
			var attrAndKeys=atts[ia].split('=');
			var key=attrAndKeys[0];
			var valkeys;
			if (attrAndKeys.length>1) {
				valkeys=attrAndKeys[1]
			}
			else {
				valkeys=attrAndKeys[0];
			}
			
			var arrKeys=valkeys.split('|')
			for (var ikey=0;ikey<arrKeys.length;ikey++) {
				if (typeof oConfig[arrKeys[ikey]] != 'undefined') {
					s[s.length]=key+'="';
					s[s.length]=(''+oConfig[arrKeys[ikey]]).replace('&','&amp;').replace('"','&quot;').replace('<','&lt;').replace('>','&gt;') ;
					s[s.length]='" ';
					break;
				}
			}
		}
		if (i+2==xs.length) { // there are no more nodes
			s[s.length]='/>';						
		}
		else {
			if (typeof xs[i+2]!='string') {
			  s[s.length]='>';
			  s[s.length]=Wildfire._BuildXMLConfigFromJSON(oConfig,xs[i+2]);
			  s[s.length]='</'+xs[i].split(' ')[0]+'>';
			  i++; // skip the array node.
			}
			else {
				s[s.length]='/>';
			}
		}
		
	}
	}
	catch(e){
//			return ('***');
	}
	return s.join('');
}

Wildfire._createJSModule = function (moduleType, partner, targetId, width, height, config, getParams)	
{	
	try {
		config.location = document.location.href;
	} catch(err) {}
	
	config.partner = partner;
	config.width = width;
	config.height = height;

	// validate input params
	if ( undef(moduleType) || undef(partner) || undef(targetId) || undef(width) || undef(height)|| undef(config)) return;

	var module = this[targetId] = this.modules[targetId] = this.modulesArray[this.modulesArray.length] = new Wildfire._JSModule();
	module.copyConfig(config);
	module.ready = false;
	module.type = moduleType;
	module.id = targetId;
	module.partner = partner;
	module.width = width;
	module.height = height;
	module.container = document.getElementById(targetId);		  
	module.container.style.width  = width + "px";
	module.container.style.height = height + "px";

	module.qsParams = new Array();
	var getParamArray = getParams.split(',');
	for (var i=0; i<getParamArray.length ; i++)
		Wildfire._addQSParam(module,getParamArray[i]);
	
	module.init(true); // true means check ping for safe mode
	return module;
};

Wildfire._origOnLoad = null;
Wildfire._onLoad = function(evt)
{
	
	Wildfire.onLoad=Wildfire._origOnLoad; //restore
	
	if (Wildfire.LinkedLoading==false) {
		if (Wildfire._origOnLoad!=null) {
			Wildfire._origOnLoad(evt);
		}
		return;
	}
	Wildfire.LinkedLoading=false;
	// this can not be called before setting Wildfire.LinkedLoading to false
	// or it might trigger additional loads while in LinkedLoading 
	if (Wildfire._origOnLoad!=null) {
		Wildfire._origOnLoad(evt);
	}
	
	if ((evt.ModuleID == Wildfire.modulesArray[0].id))
	{
		for (var i=1;i<Wildfire.modulesArray.length; i++)
		{
			if (!Wildfire.modulesArray[i].ready) 
			{
				try {Wildfire.modulesArray[i].init(true);} catch(e) {}
			}
				
		}
	}
	
};

Wildfire._createFlashModule = function (moduleType, partner, targetId, width, height, config/*, getParams*/)	
{	
	// set bookmarkURL if not set
	
	try {
		if (typeof config['bookmarkURL'] == 'undefined')
			config['bookmarkURL'] = document.location.href;
	} catch (e) {}


	// hook onLoad 
	if (Wildfire.LinkedLoading) 
	{
		if (typeof Wildfire.onLoad != 'undefined' && Wildfire.onLoad!=Wildfire._onLoad) 
			Wildfire._origOnLoad = Wildfire.onLoad;
	
		Wildfire.onLoad = Wildfire._onLoad;
	}

	var blnRecreate=false;
	var idxInArray;
	if (this.modules[targetId] != null) {
		blnRecreate=true;
		document.getElementById(targetId).innerHTML='&nbsp;';
		idxInArray=this.modules[targetId].idxInArray;
	}
	else {
		idxInArray=this.modulesArray.length;
	}
	try {
		config.location = document.location.href;
	} catch(err) {}
	
	config.partner = partner;
	config.width = width;
	config.height = height;

	// validate input params
	if ( undef(moduleType) || undef(partner) || undef(targetId) || undef(width) || undef(height)|| undef(config)) return;
	
	
	var module = new Wildfire._FlashModule();
	this.modulesArray[idxInArray] = this[targetId] = this.modules[targetId] = module;
	
	module.idxInArray=idxInArray;
	module.copyConfig(config);
	module.queued = false;
	module.ready = false;
	module.type = moduleType;
	module.id = targetId;
	module.partner = partner;
	module.width = width;
	module.height = height;
	module.container = document.getElementById(targetId);		  
	module.container.style.width  = width + "px";
	module.container.style.height = height + "px";
	
	/*
	module.qsParams = new Array();
	var getParamArray = getParams.split(',');
	for (var i=0; i<getParamArray.length ; i++)
		Wildfire._addQSParam(module,getParamArray[i]);
	*/
	if (!Wildfire.LinkedLoading || this.modulesArray.length==1 || this.modulesArray[0].ready)
	{
		module.init(true); // true means check ping for safe mode
	} else {
		module.queued = true;
	}
	return module;
};


Wildfire._raiseModulesUpdate = function() 
{
	var moduleList = "";
	for(var key in this.modules) moduleList += key + ",";
			
	var eventData = {'type':'modulesUpdate','modules':moduleList};

	this._raiseSysEvent(eventData);
}

Wildfire._raiseSysSignoutEvent = function() {
	this._raiseSysEvent({'type':'signout'});
}

Wildfire._raiseSysEvent = function(eventData) 
{
	if (this.modulesArray.length<=1) return;
	
	for(var key in this.modules) {
		var rse=this.modules[key].raiseSysEvent;
		if (rse!=null) {
			rse(eventData);
		}
	}
}

Wildfire._onFrameLoaded = function(moduleId) 
{
	var ui = document.getElementById(moduleId+"_UIFrame");
	if (ui!=null) ui.style.visibility="visible";	

	var pdiv = document.getElementById(moduleId+"_progress");
	if (pdiv!=null) pdiv.style.display = "none";

	this.modules[moduleId].UIFrame.style.visibility="visible";	
	this.modules[moduleId].applyConfig();
	this.modules[moduleId].ready = true;
	
	setTimeout("Wildfire._raiseModulesUpdate()",1500);
};

Wildfire._addQSParam = function(module,pName) {
	if ( def(typeof module.config) && def(module.config[pName]) ) {
		module.qsParams[module.qsParams.length] = pName+'='+Wildfire._URLEncode(module.config[pName]);
	}
};

Wildfire._URLEncode=function (s){
	if (encodeURIComponent) {
		return encodeURIComponent(s);
	}
	else {
		es=escape(s);
		return es.replace(/\+/g,'%2b').replace(/%20/g,'+').replace(/[/]/g,'%2f').replace(/%3D/g,'%3d');
	}
};

Wildfire._onCallback=Wildfire._raiseEvent = function(WFEvent) {
	try {
		switch(WFEvent.type)
		{
			case 'send':
				if (isnotnull(Wildfire.onSend))
					Wildfire.onSend(WFEvent);
				break;
			case 'postComment':
				if (isnotnull(Wildfire.onPostComment))
					Wildfire.onPostComment(WFEvent);
				break;
			case 'postProfile':
				if (isnotnull(Wildfire.onPostProfile))
					Wildfire.onPostProfile(WFEvent);
				break;
			case 'close':
			//debugger;
				if (isnotnull(Wildfire.onClose))
					Wildfire.onClose(WFEvent);
				break;
			case 'load':
				
				if (isnotnull(Wildfire.onLoad))
				{
					Wildfire.modules[WFEvent.ModuleID].ready = true; 
					Wildfire.onLoad(WFEvent);
				}
				break;
			case 'email':
				if (isnotnull(Wildfire.onEmail)) {
					Wildfire.onEmail(WFEvent);
				}
		}
	} catch (err) {
		//GIGYAONLY:alert('exception in _onCallback: '+err.description);
	}
};

Wildfire._Module=function() {
	// for common functionality of Flash and JS modules
}


Wildfire._JSModule= function () {
	this.formsContainer = null;
	this.pingTimeout = null;
}
Wildfire._JSModule.prototype=new Wildfire._Module();


Wildfire._FlashModule=function(){}
Wildfire._FlashModule.prototype=new Wildfire._Module();


Wildfire._JSModule.prototype.pingOK = function(ok) {
	window.clearTimeout(this.pingTimeout);
	this.config.safeMode = !ok;
	this.init(false);
}


Wildfire._FlashModule.prototype.init = function(checkPing){
	var html='';
		if ((''+this.config.isApply)!='true') {
			html += '<div style="position:relative;top:50%;text-align:center;font-size:12px;z-index:50;" id="'+this.id+'_progress"><center><img  src="'+this.config.progressImageSrc+'"></center></div>';
		}
		html += Wildfire.Flash.AC_FL_GetContent(
		'id', 'wfmodule_'+this.id,
		'name', 'wfmodule_'+this.id,
		'width', this.config.width,
		'height', this.config.height,
		'movie', 'http://cdn.gigya.com/WildFire/swf/wildfire.swf',
		'quality', 'high',  
		'align', 'middle',
		'play', 'true',
		'loop', 'true',
		'scale', 'showall',
		'wmode', (this.config.nowmode?'':'transparent'), 
		'devicefont', 'false',
		'bgcolor', ((this.config.nowmode && this.config.outsideColor)?this.config.outsideColor:'#ffffff'),
		'menu', 'true',
		'allowFullScreen', 'false',
		'allowScriptAccess','always',
		'salign', '',
		'flashvars','ModuleID='+ this.id+'&now='+(new Date()).getTime(),
		'swLiveConnect','true'
		)
	
	window['wfmodule_'+this.id] = null;
	//alert('html =' + html);
	if (!Wildfire._pixeIframeCreated) {
		html += "<iframe src='http://cdn.gigya.com/wildfire/do_not_delete.htm' style='width:0;height:0;visibility:hidden' />";
		Wildfire._pixeIframeCreated = true;
	}
		
	this._injectWFCode(html);
	//alert('Html Code  Injected');
	// ExternalInterface bug workaround - 
	window['wfmodule_'+this.id] = document.getElementById('wfmodule_'+this.id);
	//alert('window attribute set, invoking go()');
	//because the flash needs to do externalInterface calls as soon as it starts
	//we can not have it "autoExecute" or the line above this comment would not
	//be executed by the time it tries to call back.
	//window['wfmodule_'+this.id].SetVariable('_root.ready','1');
}

Wildfire._IsModuleReady=function(targetId) {
	return (window['wfmodule_'+targetId] != null)
}


Wildfire._JSModule.prototype.init = function(checkPing) 
{
	var wfroot='http://wildfire.gigya.com/wildfire';
	var id=this.id;
	var uifid=id+'_UIFrame';
	var cfg=this.config;
	
	if (!cfg.safeMode && checkPing && this.pingTimeout==null)
	{
		var script = document.createElement("script");
		script.src = wfroot+'/jsping.ashx?mid='+id + "&rand=" + Math.random() + Math.random();
		this.container.appendChild(script);
		this.pingTimeout = window.setTimeout("Wildfire.modules['"+id+"'].pingOK(false)",10000);
		return;
	}
	var qs = this.qsParams.join('&');
	qs += ("&mid="+id);
	
	var html = "";
	var formsHTML = "";
	var UIURL = wfroot+'/'+this.type + "Main.aspx?" + qs;
	if (cfg.safeMode){
		UIURL = this.getSafeModeURL();
		if (UIURL==null) {
			Wildfire[id] = Wildfire.modules[id] = Wildfire.modulesArray[Wildfire.modulesArray.length] = null;
			return null;
		}
		html += "<iframe allowtransparency='true' id="+uifid +" name="+uifid+" style='width:" + cfg.width + "px;height:" + cfg.height + "px;display:inherit;visibility:inherit' frameborder=0 scrolling=no></iframe>";
		formsHTML += "<form id='"+id+"_postForm' action='"+UIURL+"' method='POST' target="+uifid+" style='display:none'></form>";
	}
	else if (cfg.simple) {
		if (this.type=="share") UIURL = wfroot+'/shareSimple.aspx';
		if (UIURL==null) {
			Wildfire[id] = Wildfire.modules[id] = Wildfire.modulesArray[Wildfire.modulesArray.length] = null;
			return null;
		}
		html += "<iframe allowtransparency='true' id="+uifid +" name="+uifid+" style='width:" + cfg.width + "px;height:" + cfg.height + "px;display:inherit;visibility:inherit' frameborder=0 scrolling=no></iframe>";
		formsHTML += "<form id='"+id+"_postForm' action='"+UIURL+"' method='POST' target="+uifid+" style='display:none'></form>";
	} else {
		html += "<div style='position:relative;top:50%;text-align:center;font-size:12px;' id='"+id+"_progress'><center><img  src='"+cfg.progressImageSrc+"'></center></div>";
		html += "<iframe allowtransparency='true' onload='Wildfire._onFrameLoaded(\""+id+"\")' id="+uifid+" style='visibility:hidden;width:" + cfg.width + "px;height:" + cfg.height + "px;' src='"+ UIURL + "' frameborder=0 scrolling=no></iframe>";			
		html += '<iframe id="IFREndlessActivityBugFix" style="display:none;width:100px;height:10px"></iframe>';
		html += this._createCBFrame();

		formsHTML += "<form id='"+id+"_postForm' action='"+wfroot+"/WFHandler.ashx?cmd=config' method='POST' target='"+id+"_postTargetFrame' style='display:none'></form>";			
		formsHTML += "<form id='"+id+"_sysEventForm' action='"+wfroot+"/WFHandler.ashx?cmd=sysEvent' method='POST' target='"+id+"_sysEventFrame' style='display:none'></form>";
	}
	
	this._injectWFCode(html,formsHTML);	
	
	// if cant create callback frame, disable callbacks
	if (document.getElementById(id+"_wfCBFrame")==null)	{
		cfg.domainForCallback = null;
	}
		
	this.UIFrame = document.getElementById(id+"_UIFrame");
	this.postForm = document.getElementById(id+"_postForm");
	this.sysEventForm = document.getElementById(id+"_sysEventForm");
	
	if (cfg.simple || cfg.safeMode) this.applyConfig(); // normal modules get config on frame load
}

Wildfire._JSModule.prototype._createCBFrame = function() 
{
	if ( def(this.config.domainForCallback) && document.getElementById(this.id+'_wfCBDiv')==null ) 
	{
		try {
			document.domain = this.config.domainForCallback;	
			return "<iframe name='"+this.id+"_wfCBFrame' style='visibility:hidden;width:0px;height:0px;' src='http://wildfire."+this.config.domainForCallback+"/wildfire/WFHandler.ashx?domain="+escape(this.config.domainForCallback)+"'></iframe>";
			
		} catch(ex) {
			//GIGYAONLY:alert('Unable to create Iframe for callback: '+ex.description);
			return "";
		}
	} else {
		return "";
	}
}

Wildfire._FlashModule.prototype.copyConfig =  Wildfire._JSModule.prototype.copyConfig = function(config) 
{
	// clone config obj to module
	if (config!=null) {
		this.config = {};
		for(var key in config) this.config[key] = config[key];
	}

	// apply default values
	if ( undef(this.config.progressImageSrc) ) 	this.config.progressImageSrc = "http://cdn.gigya.com/WildFire/i/progress_ani.gif";
	//if ( undef(this.config.cornerRoundness) ) 	this.config.cornerRoundness=1;
	if ( undef(this.config.simple) ) this.config.simple = navigator.userAgent.toLowerCase().indexOf('safari')!=-1;
}

Wildfire._JSModule.prototype.getSafeModeURL = function(){
	if (this.type=="share") return "http://backup.gigya.com/WFSimple/share.aspx";
	return null;
}

// check if page already has 'form' tag, if yes, insert div to contain our forms, outside of it.
Wildfire._JSModule.prototype._injectWFCode= function(html,formsHTML){
	var el=this.container;
	for(;((el!=null) && ((''+el.tagName).toLowerCase() !='form'));el=el.parentNode);
	if (el!=null) { 
		this.container.innerHTML = html;
		this.formsContainer = document.createElement('div');
		this.formsContainer.style.display='none';
		el.parentNode.insertBefore(this.formsContainer,el);
		this.formsContainer.innerHTML = formsHTML;
		
	} else
	{
		this.container.innerHTML = html + formsHTML;
	}
};


Wildfire._FlashModule.prototype._injectWFCode= function(html){
	this.container.innerHTML = html;
};

Wildfire._JSModule.prototype.raiseSysEvent = function(eventData){
	if (this.sysEventForm==null || !this.ready)  return;
	
	var s = new Array(); var i=0;
	for(var key in eventData) {
		if (typeof key != 'function' && eventData[key]!=null) {
			s[i++] = "<input type=hidden name='"+key+"'/>"
		}
	}
	
	this.sysEventForm.innerHTML = s.join('');

	//set value (using foo.value handles escaping of strings better...)
	for (var i=0;i<this.sysEventForm.length; i++) {
		this.sysEventForm[i].value = eventData[this.sysEventForm[i].name];
	}
	this.sysEventForm.submit();
};

Wildfire._FlashModule.prototype.applyConfig = function(conf){
	conf.isApply="true";
	return Wildfire._createFlashModule(this.type, this.partner, this.id, this.width, this.height, conf);
};

Wildfire._JSModule.prototype.applyConfig = function(conf){
	if (conf!=null) this.copyConfig(conf);
	var cfg=this.config;
	if (cfg==null) return;
	if (cfg.location==null || cfg.location=="")	{
		try { cfg.location = document.location.href;} catch(err) {}
	}

	cfg.partner = this.partner;
	cfg.width	= this.width;
	cfg.height	= this.height;

	// check if templates are IDs or actual values
	// For Post
	postContent=['default','myspace','hi5','friendster','xanga','livejournal','freewebs','facebook','bebo','blogger','tagged','typepad','blackplanet'];
	for (var pci=0;pci<postContent.length;pci++){
		this._getTemplate(postContent[pci] + 'Content');
	}
	//For Share
	shareTemplates=['default','comment','email','myspace','hi5','friendster','xanga','freewebs'];
	for (var sti=0;sti<shareTemplates.length;sti++){
		this._getTemplate(shareTemplates[sti]+ 'Template');
	}

	// build config fields
	var s = new Array(); var i=0;
	for(var key in cfg) {
		if (typeof key != 'function' && cfg[key]!=null) {
			s[i++] = "<input type=hidden name='"+key+"'/>"
		}
	}

	this.postForm.innerHTML = s.join('');

	//set value (using formfield.value handles escaping of strings better...)
	for (var i=0;i<this.postForm.length; i++) {
		this.postForm[i].value = this.config[this.postForm[i].name];
	}
	this.postForm.submit();
	
	window.setTimeout('Wildfire._EndlessActivityBugFix();',1000);
};

Wildfire._EndlessActivityBugFix=function(){
	var ifr=document.getElementById('IFREndlessActivityBugFix');
	if (ifr!=null) {
		ifr.src='http://cdn.gigya.com/wildfire/i/n.gif';
	}
};

Wildfire._JSModule.prototype._getTemplate = function (key) {
	if ( isnotnull(this.config[key]) ) {
		try {
			if ( isnotnull(document.getElementById(this.config[key])) )
				this.config[key] = document.getElementById(this.config[key]).value;
		} catch (e) {
			//GIGYAONLY:alert('Unable to get template for key :'+ key + '\n' + ex.description);
		}
	}
};

Wildfire._CopyAtts=function(t,s,atts){ for(k in atts.split(',')){ t[atts[k]]=s[atts[k]]; }}
Wildfire._CopyAllAtts=function(t,s){for(k in s) {t[k]=s[k];}}

function undef(o) { return (typeof(o)=='undefined');}
function def(o) { return (typeof(o)!='undefined');}
function isnotnull(o) { return (def(o) && (o!=null));}

function WFQueue(){
  var queue=new Array();
  var queueSpace=0;
  this.count=function()
  {
	return queue.length;
  }
  this.enqueue=function(element){
    queue.push(element);
  }
  this.dequeue=function(){
    if (queue.length){
      var element=queue[queueSpace];
      if (++queueSpace*2 >= queue.length){
        for (var i=queueSpace;i<queue.length;i++) queue[i-queueSpace]=queue[i];
        queue.length-=queueSpace;
        queueSpace=0;
      }
      return element;
    }else{
      return undefined;
    }
  }
}

////////////////////////////
//  Wildfire Post Button
///////////////////////////

Wildfire._hideWildfirePopup = function() {
    document.getElementById('wildfire_postDiv').style.display = 'none';
}

Wildfire._popupConfigs = [];

Wildfire.renderPostButton = function(partner, width, height, config) {
    config.showCloseButton = true;
    Wildfire._popupConfigs.push(config);
    var configID = Wildfire._popupConfigs.length - 1;
    document.write('<img id="Wildfire_Button' + configID + '" src="http://cdn.gigya.com/wildfire/i/post-to-button.gif" style="cursor: pointer" onclick="Wildfire._showWildfirePopup(' + ["'" + partner + "'", width, height, configID].join(', ') + ')" border=0 alt="Post to my social network or blog" title="Post to my social network or blog" />');
}

Wildfire._lastID = 0;

Wildfire._getScrollXY=function() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

Wildfire._showPopup = function(w, h) {
	var wfDiv=document.getElementById('wildfire_postDiv');
	var dst;
	if (wfDiv) {
		dst=wfDiv.style;
	} else {
        wfDiv = document.createElement('div');
        wfDiv.id = 'wildfire_postDiv';
        wfDiv.style.position = 'absolute';
        wfDiv.style.display = 'none';
        wfDiv.style.zIndex = 999999;
        if (document.body != null) document.body.insertBefore(wfDiv,document.body.firstChild);	
	}
    
    dst=wfDiv.style;
    
	var vph;
	var vpw;
	var de=document.documentElement;
	
	vph=de.clientHeight;
	vpw=de.clientWidth;
	if (typeof vph=='undefined' || vph==0) {
		vph=document.body.clientHeight;
		vpw=document.body.clientWidth;
	}
	if (typeof vph=='undefined' || vph==0) {
		vph=window.innerHeight;
		vpw=window.innerWidth;
	}
	
	scrl=Wildfire._getScrollXY();
	
	var vpt=scrl[1];
	var vpl=scrl[0];
	
	dst.top=''+(vpt+Math.floor((vph-h)/2))+'px';
	dst.left=''+(vpl+Math.floor((vpw-w)/2))+'px';
	dst.width=''+w+'px';
	dst.height=''+h+'px';
}

Wildfire._showWildfirePopup = function(partner, width, height, configID) {
    Wildfire._showPopup(width, height);
    Wildfire.onClose = Wildfire._hideWildfirePopup;
    Wildfire.initPost(partner, 'wildfire_postDiv', width, height, Wildfire._popupConfigs[configID]);
    var popDiv = document.getElementById('wildfire_postDiv');
    popDiv.style.display = "";
}

//inject CIMP
Wildfire._injectCIMP = function() {
    if (document.getElementById('wildfire_cimp') == null && document.body != null) {
        var cimp = document.createElement('div');
        cimp.id = 'wildfire_cimp';
        cimp.width = 1;
        cimp.height = 1;
        cimp.style.display = 'none';
        cimp.style.visibility = 'hidden';
        cimp.style.position = 'absolute';
        cimp.innerHTML = '<img src="http://counters.gigya.com/wildfire/i/CIMP.gif" />';
        document.body.insertBefore(cimp,document.body.firstChild);
    }
}

$j(window).load(function(){
	window.setTimeout(function(){Wildfire._injectCIMP();},10000);	
})