// Community Object
var Site = function(abbr) {
	this.cid = ''
	this.ciid = ''
	this.uid = ''
	this.abbr = abbr
	this.title = ''
	this.usernameName = '0'
	this.usernamePrompt = ''
	this.hasSubject = false
	this.isLoggedIn = false

	this.getForm = function() {
		if (!this._form) {
			this._form = $(this.abbr + 'form')
		}
		return this._form
	}

	this.form = this.getForm()

	this.hasBulletin = false
	this.widgetType = '1'

	this.defaultFeedbackMsg = ''

	this.widgetName = 'Slide Show'
	this.askBlogs = false
	this.askInterests = false


	// feedback related
	this._postTarget = ''
	this.getPostTarget = function() { return this._postTarget }
	this.setPostTarget = function(tgt) { this._postTarget = tgt }
	this.clearPostTarget = function() { this._postTarget = '' }

	this.displaySection = function() {}
	this.resetSection = function() {
		if (this.form.section){
			for (var i=0; i< this.form.section.options.length; i++) {
				var node = this.form.section.options[i];
				if (node.value && (node.value.charAt(0) != "-")) {
					this.form.section.value = node.value;
					return;
				}
			}
		}
	}

	this.set_widget_name = function(name) {
		this.widgetName = name
	}

	this.get = function(objId) {
		return $(this.abbr + objId)
	}

	this.isComments = function() {
		return this.getPostTarget() == 'comments';
	}

	// see other .success() definitions in this file and community.js
	this.success = function(ans) {
	  // postembed_url is defined in the basechannel template
	  var redirect = postembed_url + '&cy=' + this.abbr;
	  if( parent.parent ){
	    parent.parent.location.href = redirect;
	  }else{
	    parent.location.href = redirect;
	  }

	}

	// display a link back to the site we just embedded on
	// should generalized but for the time being this is exclusive to bebo
	this.displayLinkBack = function() {
		var l = parent.$('bebolinkback')
		if (l) {
			l.style.display = (this.abbr == 'be') ? 'block' : 'none'
		}
		var a = parent.$('beboadvert')
		if (a) {
			a.style.display = (this.abbr == 'be') ? 'none' : 'block'
		}
	}

	this.failure = function(returnCode) {
		if (returnCode && (!this.askInterests && !this.askBlogs) && (returnCode == 'FAIL:TIMEOUT' || returnCode == 'FAIL:COMMFAIL')) {
			this.showRetry()
		} else {
			displayDimmed('errorPopup');
		}
	}

	this.setForm = function(frm) {
		cFrm = this.form
		if (cFrm.username) cFrm.username.value = valueOf(frm.username)
		if (cFrm.password) cFrm.password.value = valueOf(frm.password)
		if (cFrm.section) cFrm.section.value = valueOf(frm.section)
		if (cFrm.blogID) cFrm.blogID.value = valueOf(frm.blogID)
		if (cFrm.bulletin) cFrm.bulletin.value = valueOf(frm.bulletin)
		if (cFrm.subject) cFrm.subject.value = valueOf(frm.subject)
	}

	this.setVals = function() {
		createCookie(this.abbr + 'usr-' + this.uid, this.form.username.value, 0)
		createCookie(this.abbr + 'pwd-' + this.uid, this.form.password.value, 0)
	}

	this.readVals = function() {
		this.form.username.value = readCookie(this.abbr + 'usr-' + this.uid)
		this.form.password.value = readCookie(this.abbr + 'pwd-' + this.uid)

		var auth = this.checkAuth()
		if (auth != '') {
			this.form.auth.value = auth
		}
	}

	this.checkAuth = function() {
		var exp = this.abbr + "-token(\.[^=]+)=([a-zA-Z0-9-_]+)"
		var re = new RegExp(exp)
		var ck = re.exec(document.cookie);

		return ck ? ck[2] : ''
	}

	this.authAlterDisplay = function() {
		if (this.checkAuth() != '') {
			this.get('authbox').style.display = 'none'

			var sa = this.get('submitarea')
			sa.style.cssFloat = 'right'
			sa.style.styleFloat = 'right'
			sa.style.padding = '0 100px 0 0'

			this.get('submit').style.marginTop = '5px'

			var sba = this.get('subjectarea')
			sba.style.clear = 'none'
			sba.style.paddingLeft = '50px'
		}
	}

	this.showFeedback = function(msg) {
		this.setVals()
		var fbmsg = this.get('feedbackmsg')
		if (msg) {
			fbmsg.innerHTML = msg
		} else {
			fbmsg.innerHTML = this.defaultFeedbackMsg
		}
		this.get('feedback').style.display = 'block'
		this.get('controls').style.display = 'none'
		return true;
	}

	this.hideFeedback = function() {
		this.get('feedback').style.display = 'none'
		this.get('controls').style.display = 'block'
		return true;
	}

	// see also .submitPost in basechannel.tmpl, and .handlePost() below
	this.submitPost = function() {
		this.showFeedback()
		return this.post()
	}

	this.postComments = function() {
		if (!this.getBlogIDs().length) {
			alert(cl.Mscd.No_Friend_Selected)
			return false;
		}
		this.showFeedback()
		return this.post(false, false, false, true)
	}

	this.alertError = function(msg, field) {
		this.hideFeedback()
		alert(msg)
		field.focus()
		return false;
	}

	this.getBlogIDs = function() {
		var blogIDs = this.form.elements;
		var ids = [];
		for (var i = 0; i< blogIDs.length; i++) {
			blogID = blogIDs[i];
			if ((blogID.name == "blogID") && blogID.checked) {
				ids.push(blogID.value);
			}
		}
		return ids
	}

	this.getCorrectInterestID = function() {
		return this.getPostTarget() == 'comments' ? 'none' : (valueOf(this.form.section) || 'none')
	}

	this.setCorrectBlogID = function() {
		if (this.blogID_override){
			this.blogID = this.blogID_override;
			return;
		}
		var blogID = valueOf(this.form.blogID) || 'none'

		if (this.allowsMultiBlog) {
			blogID = this.getBlogIDs().join(",");
		} else if (this.blogAsSection) {
			blogID = (valueOf(this.form.section) == "none") ? "unnamed" : "none";
		} else if (blogID == 'none' && this.hasBlog) {
			blogID = 'unnamed'
		}
		if (this.allowsComments && !this.getPostTarget()) {
			blogID = 'none'
		}
		if (this.hasBulletin && valueOf(this.form.bulletin) && !this.getPostTarget()) {
			blogID = 'bulletin'
		}
		this.blogID = blogID;
	}

	// part of response to ajax call
	this.post = function(alwaysadd, getBlogs, getInterests) {
		this.always_add = alwaysadd ? true : false
		this.widget_log_embed_success = this.form.widget_log_embed_success ? this.form.widget_log_embed_success.value : '905';
		this.widget_log_embed_failure = this.form.widget_log_embed_failure ? this.form.widget_log_embed_failure.value : '913';
		this.widget_log_embed_id = this.form.widget_log_embed_id ? this.form.widget_log_embed_id.value : '0';
		this.ad_type = this.form.ad_type ? this.form.ad_type.value : '0';

		var subj = valueOf(this.get('subject'))
		if (!subj && this.hasSubject && (!this.hasBulletin || valueOf(this.form.bulletin))) {
		   this.hideFeedback();
		   alert('You must enter a ' + (this.hasBulletin ? 'subject if you want to send a bulletin' : 'title if you want to post an entry' ));
		   return false;
		}
		var body = (this.isComments()) ? getCommentCode() : getTickerCode();

		this.auth = this.form.auth.value
		this.username = strtrim(this.form.username.value)
		this.password = this.form.password.value

		if (!this.username && !this.auth) return this.alertError('Please enter a valid ' + this.usernameName, this.form.username)
		if (!this.password && !this.auth) return this.alertError('Please enter a password', this.form.password)

		this.xaction = 'cembed'
		if (getBlogs) this.xaction = 'getuserblogs'
		if (getInterests) this.xaction = 'getuserinterests'
		if (this.allowsComments && !this.getPostTarget()) this.xaction = 'embed_fetch_blogs'

		this.setCorrectBlogID()

		var parentObj = this;
		asyncAction('scrapeajax', {
			xaction : this.xaction,
			next_view : 'MSCD',
			community : this.abbr,
			username   : this.form.username.value,
			password : this.form.password.value,
			auth : this.form.auth.value,
			blogID : this.blogID,
			interestID : this.getCorrectInterestID(),
			body :  body,
			on_top :  valueOf(this.form.on_top) || 'true',
			subject : subj || '',
			widget_log_embed_success : this.widget_log_embed_success,
			widget_log_embed_failure : this.widget_log_embed_failure,
			widget_log_embed_id : this.widget_log_embed_id,
			ad_type : this.ad_type,
			always_add : this.always_add,
			channel_id : this.cid,
			channel_item_id : this.ciid,
			sessionID : valueOf(this.form.sessionID),
			captcha : valueOf(this.form.captcha),
			partner : valueOf(this.form.partner),
			referrer : String(window.location) },
			function(theResponse) {
				parentObj.hideFeedback()
				if (parentObj.xaction == 'getuserblogs' && theResponse.substr(0,4) == 'PASS') {
					parentObj.displayBlogs(evalJSON(theResponse.substr(5)))
				} else if (parentObj.xaction == 'getuserinterests' && theResponse.substr(0,4) == 'PASS') {
					parentObj.displayInterests(evalJSON(theResponse.substr(5)))
				} else {
					parentObj.handlePost(theResponse)
				}});
		return false;
	}

	// see also submitPost()
	this.handlePost = function(ans) {
		var siteName = this.usernamePrompt
		var usernameLabel = this.usernameName

		if (ans.substring(0,4) == "PASS") {
			this.success(ans)
		} else if (ans.substring(0,5) == "LATER") {
			this.success(ans)
		} else if (ans == "FAIL:ALREADY") {
			if (confirm('This ' + this.widgetName + ' is already added to ' + siteName + '. Sure you want to add again?')) {
				this.showFeedback();
				this.post(true)
			}
		} else if (ans.substring(0,15) == "FAIL:TRYCAPTCHA") {
		       this.trycaptcha(ans)
		} else if (ans.substring(0,12) == "FAIL:CAPTCHA") {
			var captchaStr = ans.substring(14).split(' ', 2)
			if (captchaStr != '') {
				this.captcha(captchaStr)
			} else {
				parent.displayDimmed('captchaPopup')
			}
		} else if (ans == "FAIL:NOLOGIN") {
			alert('Incorrect ' + usernameLabel.toLowerCase() + ' or password. \n\nBe sure to use your ' + siteName + ' ' + usernameLabel.toLowerCase() + ' and password, NOT your Slide ' + usernameLabel.toLowerCase() + ' and password')
		} else if (ans == "FAIL:FORMAT SUBJECT") {
			alert('The subject must be all ASCII characters.')
		} else if (ans == "FAIL:MAXEDLIMIT"){
			alert('You cannot add any more ' + this.widgetName + 's to ' + siteName + '. Please clear out some room.')
		} else {
			parent.displayDimmed('errorPopup');
		}
	}

	this.trycaptcha = function(ans) {
		cap = evalJSON(ans.substring(16));
		parent.setCaptchaTry(cap);
	}

	this.captcha = function(parms) {
		this.get('captcha_img').src = parms[1]
		this.form.sessionID.value = parms[0]
		this.get('loginarea').style.display = 'none'
		this.get('captcha').style.display = 'block'
	}

	this.fillOptions = function(selectObj, options) {
		if (selectObj.type == "select-one") {
			this.fillSingleOptions(selectObj, options);
		} else {
			this.fillMultiOptions(selectObj, options);
		}
	}

	// create checkboxes, one for each of the user's friends, in a table inside the selectObj.
	// options is an array of objects, one for each check:
	// [friendid, friendname, selected, portraiturl] only first two are required
	this.fillMultiOptions = function(selectObj, options) {
		var capAt = 25;  // max option name length
		var optionsTable = null
		var currentRow = null
		this.addSelectLinks(selectObj)

		appendChildNodes(
			selectObj,
				TABLE({
					cellspacing : 0,
					cellpadding : 0,
					width: (document.all) ? "90%" : "100%"
					},
					optionsTable = TBODY(null)))

		for (i = 0; i < options.length; i++) {
			if (!(i % 3)) {
				appendChildNodes(
					optionsTable,
						currentRow = TR(null))
			}

			var checkboxAttr = {
				type 	: "checkbox",
				value	: options[i][0],
				name	: "blogID",
				"class"	: this.abbr + 'check'
				}

			// the third value in the select object defines selection state if present
			if (options[i][2] == undefined || options[i][2] == true) {
				checkboxAttr['checked'] = 'checked';
			}

			appendChildNodes(
				currentRow,
					TD(null,
						INPUT(checkboxAttr),
						SPAN(null, options[i][1].substr(0,capAt) + ((options[i][1].length > capAt) ? '...' : ''))))
		}
		if (options.length > 12) {
			this.addSelectLinks(selectObj)
		}
	}

	this.addSelectLinks = function(obj) {
		appendChildNodes(
			obj,
				P({ style: "margin: 3px 5px; font-size: 8pt; "},
					A({
						href 	: "#",
						onclick : "parent.logSelectAllCheckboxes(); return setAllCheckboxes('" + this.abbr + "check', true)"
						}, cl.Mscd.Select_all),
					" | ",
					A({
						href 	: "#",
						onclick : "parent.logUnSelectAllCheckboxes(); return setAllCheckboxes('" + this.abbr + "check', false)"
						}, cl.Mscd.Unselect_all)))
	}

	this.fillSingleOptions = function(selectObj, options) {
		var capAt = 35
		for (i = 0; i < options.length; i++) {
			var currentOption = createElement(selectObj, "option")
			var currentOptionTitle = options[i][1]
			currentOptionTitle = (currentOptionTitle.length > capAt) ? currentOptionTitle.substr(0,capAt) + "..." : currentOptionTitle
			currentOption.value = options[i][0]
			currentOption.innerHTML = currentOptionTitle
		}
	}

	this.setCorrectPageSize = function() {
		if (typeof(parent.resizeIframe) != 'undefined') parent.resizeIframe(document.body.offsetHeight)
	}

	this.hideLogin = function() {
		this.isLoggedIn = true
		this.get('loginarea').style.display = 'none'
		this.get('loggedusername').innerHTML = this.form.username.value
		this.get('loginchange').style.display = 'block'
		this.displaySection()
	}

	this.showLogin = function() {
		this.isLoggedIn = false
		this.get('loginchange').style.display = 'none'
		this.get('skipblogs').style.display = "none";
		this.form.username.value = ''
		this.form.password.value = ''
		if (this.get('Select')) this.get('Select').innerHTML = ''
		if (this.askInterests) this.get('section').innerHTML = ''
		this.blogID = null
		this.get('loginarea').style.display = 'block'
		this.displaySection()
		this.clearPostTarget()
	}

	this.displayBlogs = function(blogs) {
		this.blogs = blogs;
		this.hideLogin()
		this.get('skipblogs').style.display = "inline";
		this.fillOptions(this.get('Select'), blogs)
		this.get('submit').value = cl.Mscd.Add
		this.get('blog').style.display = "block"
		if (this.hasSubject && !this.allowsComments) {
			this.get('subjectarea').style.visibility = "visible"
		}
	}
	this.skipBlogs = function() {
		this.get('skipblogs').style.display = "none";
		this.showLogin();
		this.resetSection();
		this.success();
	}
	this.displayInterests = function(interests) {
		this.hideLogin()
		this.fillOptions(this.get('section'), interests)
		this.get('submit').value = cl.Mscd.Add
		this.get('section').style.display = 'block'
		this.get('sectionlabel').style.display = 'block'
	}

	// Retry
	this.showRetry = function() {
		this.get('retry').style.display = "block"
	}

	this.retryPost = function() {
		rw = window.open('/retry?site=' + this.abbr + '&cid=' + this.cid + (this.ciid ? '&ciid=' + this.ciid : '') + '&type=' + this.widgetType, 'retry' + this.abbr, 'width=330,height=200,toolbar=no,scrollbars=no,resizable=no,directories=no,menubar=no')
		this.initRetry(0, rw)
		this.get('retry').style.display = 'none'
	}

	this.initRetry = function(counter, windowref) {
		isReady = (counter > 0) ? windowref.document.getElementById('autoEmbedCode') : false
		if (counter < 6) {
			if (!isReady) {
				thisObj = this
				setTimeout(function() { thisObj.initRetry(this.form, counter+1, windowref)}, 1000)
			} else {
				rs = windowref.retrySite
				rs.setForm(this.form)
				windowref.setTickerCode(getTickerCode());
				windowref.retrypost(5)
			}
		}
	}
}

var setAllCheckboxes = function(cl, v) {
	forEach(getElementsByTagAndClassName("input", cl),
		function(box) { box.checked = v } );
	return false;
}

function showInstruction(id) {
	var gr = $('group');
	var pr = $('profile');
	var cm = $('comment');
	var bn = $('band');

	gr.style.display = (id == 'group')	? "" : "none";
	pr.style.display = (id == 'personal') 	? "" : "none";
	cm.style.display = (id == 'comment') 	? "" : "none";
	bn.style.display = (id == 'band') 	? "" : "none";
}

var getTickerCode = function() {
	return $('z').codebox.value
}

var getCommentCode = function() {
	return $('z').commentbox.value || $('z').codebox.value ;
}

var checkIfBlank = function(frm, fld, name) {
	if (!frm[fld].value) {
		alert('Please provide ' + name);
		frm[fld].focus();
		frm[fld].select();
		return true;
	}
	return false;
}


var checkIsEmail = function(frm, fld) {
	var v = frm[fld].value;
	if (v && !isLegalEmails(v)) {
		alert('Please provide email addressess of the form name@site.com');
		return true;
	}
	return false;
}

var emailFriends = function(frm) {
	if (frm.addresses.value == '' && frm.addresses1.value == '' && frm.addresses2.value == '') {
		alert('Please provide at least one email address')
		return false;
	}

	if (checkIfBlank(frm, "sender", "a From address")
	    || checkIfBlank(frm, "subject", "a Subject")
	    || checkIfBlank(frm, "message", "a Message")) {
			return false;
		}

	if (checkIsEmail(frm, "addresses")
	    || checkIsEmail(frm, "addresses1")
	    || checkIsEmail(frm, "addresses2")) {
			return false;
		}

	var parms = {'action'    : 'sendemail',
				 'addresses' : frm.addresses.value + "," + frm.addresses1.value + "," + frm.addresses2.value,
				 'sender'    : frm.sender.value,
				 'subject'   : frm.subject.value,
				 'message'   : frm.message.value,
				 'cid'		 : frm.cid && frm.cid.value || '',
				 'pxcid'     : frm.pxcid && frm.pxcid.value || ''
	};
	if (frm.pxciid) {
		parms['pxciid'] = frm.pxciid.value;
	}

	ajaxAction('channelajax',
			   parms ,
			   function(theResponse) {
				   ShowUpdate(frm, 0, 0, 'The email has been sent.');
				   $('addresses').value = ''
				   $('addresses1').value = ''
				   $('addresses2').value = ''
			   },
			   function(theResponse) {
				   if (theResponse.substring(0,19) == 'FAIL:FORMAT SUBJECT') {
					   alert(badSubjectMessage);
				   } else {
					   alert(theResponse)
				   }
			   });
	return false;
}

var badSubjectMessage = "Subject must be ASCII characters";

var logHit = function(name, query) {
	asyncAction('userajax',
		{	xaction	: 'dohitlog',
			name	: name,
			query 	: query });
	return false
}

var toggleInstructions = function() {
	var instructionsDiv = $('diy')
	var initialState = instructionsDiv.style.display
	instructionsDiv.style.display = (initialState == 'none') ? 'block' : 'none'
	$('showHide').innerHTML = (initialState == 'none') ? 'Hide' : 'See'
	logHit('mscd_instr|click','$channel.id')
	return false;
}


var showAltInstruction = function(setting) {
	var div;
	var i = 0;
	while ( (div = $("instructionpage" + i)) ) {
		if (i == setting) {
			div.style.display = "block";
		} else {
			div.style.display = "none";
		}

		i++;
	}
	if (parent.resizeIframe) parent.resizeIframe(document.body.offsetHeight);

	return false;
};


/* Querying select for its value doesn't return the text for the option, only its value. This does. */
var getOptionText = function(field) {
	if (field.options) {
					for (i = 0; i < field.options.length; i++) {
							if (field.value == field.options[i].value) return field.options[i].text
					}
	}
}

var cleanText = function(s) {
	var rv = '';
	if (s) {
		for (var i=0; i<s.length; i++) {
			if (s.charCodeAt(i) < 127) {
				rv += s.charAt(i);
			}
		}
	}
	return rv;
};


var channelEmbedded = function(channel_id) {
	var prev_embed = readCookie('slide_channel_embed_cookie');

	if (prev_embed == channel_id) {
	    return true;
	}
		
	createCookie('slide_channel_embed_cookie', channel_id, 0);
	return false;
}
