var PLUCK = function() {
	var $S = CBC.SETTINGS;
	var $U = CBC.UTIL;
	var $D = CBC.DOM;
	var $E = CBC.EVENT;
	var $A;
	var $ = $U.getElementsById;

	return {
		init: function(_params) {
			try {
				if ($S.getVal("pluckEnabled")) {
					var body = document.body;
					var bodyId = body.id || (body.id = "cbc");
					CBC.EVENT.onContentReady(bodyId, this.discoverPluck,{modules:_params});
					if ($S.getVal("colourTheme")) $D.addClass(body, $S.getVal("colourTheme"));
					if ($('p-loginwrap')) $('p-loginwrap').innerHTML = (this.isLoggedIn()) ? $S.getVal("tpl_loggedin_link") : $S.getVal("tpl_notloggedin_link");
					if ($('p-registerwrap')) $('p-registerwrap').innerHTML = $S.getVal("tpl_register_link");
				}
			} catch(e) { $U.debug(e); }
		},

		discoverPluck: function(_params) {
			try {
				var _modules = _params.modules;
				//adding site catalyst settings object as first module to list if not yet defined there
				if (_modules && _modules.length > 0) {
					// if(CBC.APP.PLUCK.searchArray(_modules,'p-sitecatalyst') == -1) { _modules.splice(0,0,'p-sitecatalyst'); }
					for (var i=0; i<_modules.length; i++) CBC.loadAssets({_src:$S.getVal(_modules[i]).loader._src,_nameSpace:CBC.APP.PLUCK});
					CBC.register({_name:'SiteCatalystSettings',_class:SiteCatalystSettings,_nameSpace: CBC.APP.PLUCK});
				}
				if ($S.getVal("cbcModule") != "storywrapper" && $S.getVal("cid") && ( CBC.APP.PLUCK.searchArray(_modules, "p-article") != -1||CBC.APP.PLUCK.searchArray(_modules, "p-comments") != -1 )) CBC.APP.PLUCK.discoverArticle($S.getVal("cid"));
			} catch(e) { $U.debug(e); }
		},

		privilegedObj: function(_obj) {
			//to access private properties
			return eval(_obj);
		},

		discoverArticle: function(_cid) {
			try {
				var rb = new RequestBatch();
				var ak = new ArticleKey(_cid);

				rb.AddToRequest(ak);
				rb.BeginRequest($S.getVal("serverUrl"),function(_responseBatch) {

					if (_responseBatch.Responses.length > 0) {
						var article = _responseBatch.Responses[0].Article;

						if (!article.PageTitle) {
							CBC.APP.PLUCK.updateArticle(_cid);
						} else {

							var cbc_article_title = $S.getVal("articleTitle");

							if (!cbc_article_title) return;

							var cbc_article_url = document.location.href;
							var _index = cbc_article_url.indexOf("#");

							if (_index > 0) cbc_article_url = cbc_article_url.substring(0,_index);

							var cbc_article_sec_name = ($S.getVal("articleSection")) ? $S.getVal("articleSection") : "";
							var cbc_article_check =  cbc_article_title + " | " + cbc_article_url + " | " + cbc_article_sec_name + " | ";
							var _cats = ($S.getVal("articleCategories")) ? $S.getVal("articleCategories") : "";

							if (_cats) {
								for (var i=0; i<_cats.length; i++) cbc_article_check += _cats[i];
							}

							var sitelife_article_sec_name = (article.Section) ? article.Section.Name : "";
							var sitelife_article_check = article.PageTitle + " | " + article.PageUrl + " | " + sitelife_article_sec_name + " | ";

							for (var i=0; i<article.Categories.length; i++) sitelife_article_check += article.Categories[i].Name;

							if (cbc_article_check != sitelife_article_check) CBC.APP.PLUCK.updateArticle(_cid);

						}

					} else {
						CBC.APP.PLUCK.updateArticle(_cid);
					}
				});

			} catch(e) { $U.debug(e); }

		},

		updateArticle: function(_cid) {
			var pagetitle = ($S.getVal("articleTitle")) ? $S.getVal("articleTitle") : document.getElementsByTagName("title")[0].innerHTML;
			var pageurl = document.location.href;
			var section = null;
			var categories = null;
			var rb = new RequestBatch();
			var ak = new ArticleKey(_cid);

			if ($S.getVal("articleSection")) {
				section = new Section($S.getVal("articleSection"));
				var articleCategories = ($S.getVal("articleCategories")) ? $S.getVal("articleCategories") : null;
				if (articleCategories) {
					categories = [];
					for (var i=0; i<articleCategories.length; i++)
						categories[i] = new Category(articleCategories[i]);
				}
			}

			$U.makeRequest( $S.getVal("proxyRelUrl"), { context: this, success:this.updateArticleSuccess, failure:this.updateArticleFailure }, "" );

		},

		updateArticleSuccess: function() { },
		updateArticleFailure: function() { },

		spawnLogin: function(_el, _theme, _module) {

			var callback = 'handleLogin';
			var instance = '';

			if (CBC.APP.PLUCK.Comments && !CBC.APP.PLUCK.Photogallery) {
				instance = 'pluckcomments';
			} else if (CBC.APP.PLUCK.Forums) {
				instance = 'pluckforums';
			} else if (CBC.APP.PLUCK.Photogallery) {
				instance = 'pluckphotogallery';
			} else if (CBC.APP.PLUCK.Videouploader) {
				instance = 'pluckvideouploader';
			} else if (CBC.APP.PLUCK.Ratings) {
				instance = 'pluckratings';
			}

			YUI(_CBC_LOADER).use('cbc_auth', function(Y,result) {
				if (!$A) {
					$A = new Y.CBC.Util.Auth();
					CBC.APP.Instances.add("authwrap",$A);
				}
				$A.spawnLogin({Y:Y,cb:callback,iname:instance});
			});

		},

		submitLogin: function(_el,_o) {
			try {
				var _form = $D.getAncestorByTagName(_el,"form");
				$U.resetFields([_form["Username"], _form["Password"]], "error");
				if ($U.validateField(_form["Username"],"")) return;
				if ($U.validateField(_form["Password"],"")) return;
				_form["LoginPageURL"].value = _form["LoginPageURL"].value.replace(/&u=([^&]*)/gi,"") + '&u=' + _form["Username"].value;
				$U.getElementsByClassName("wrap",'mclogin',"div")[0].style.display = "none";
				$U.getElementsByClassName("logging",'mclogin',"div")[0].style.display = "block";
				_form.submit();
			} catch(e) { $U.debug(e); }
		},

		closeLogin: function(_el) {
			try {
				$('mclogin-wrap').className = "d-none";
			} catch(e) { $U.debug(e); }
		},
		handleGlobalnavLogin: function(){
			try {
				if (CBC.APP.Instances.get("globalnav")) CBC.APP.Instances.get("globalnav").handleLogin();
			} catch(e) {
			}
		},
		handleLogin : function() {
			if (CBC.APP.PLUCK.Comments && !CBC.APP.PLUCK.Photogallery) {
				CBC.APP.PLUCK.Comments.handleLogin();
			} else if (CBC.APP.PLUCK.Forums) {
				CBC.APP.PLUCK.Forums.handleLogin();
			} else if (CBC.APP.PLUCK.Photogallery) {
				CBC.APP.PLUCK.Photogallery.handleLogin();
			} else if (CBC.APP.PLUCK.Videouploader) {
				CBC.APP.PLUCK.Videouploader.handleLogin();
			} else if (CBC.APP.PLUCK.Ratings) {
				CBC.APP.PLUCK.Ratings.handleLogin();
			}
		},
	
		spawnRegister: function(_el, _theme, _module) {
			var callback = 'handleLogin';
			var instance = '';

			if (CBC.APP.PLUCK.Comments && !CBC.APP.PLUCK.Photogallery) {
				instance = 'pluckcomments';
			} else if (CBC.APP.PLUCK.Forums) {
				instance = 'pluckforums';
			} else if (CBC.APP.PLUCK.Photogallery) {
				instance = 'pluckphotogallery';
			} else if (CBC.APP.PLUCK.Videouploader) {
				instance = 'pluckvideouploader';
			} else if (CBC.APP.PLUCK.Ratings) {
				instance = 'pluckratings';
			}

			YUI(_CBC_LOADER).use('cbc_auth', function(Y,result) {
				if (!$A) {
					$A = new Y.CBC.Util.Auth();
					CBC.APP.Instances.add("authwrap",$A);
				}
				$A.spawnRegister({Y:Y,cb:callback,iname:instance});
			});

		},

		closeRegister: function(_el) {
			$('mcregister-wrap').className = "d-none";
		},

		handleRegisterSuccess: function() {
			$D.addClass('mcregister-wrap', "complete");
		},

		completeRegistration: function() {
			$('mcregister-wrap').className = "d-none";
			if ($('MC_standalone_module')) $('MC_standalone_module').style.display = "none";
			register_callback();
		},

		refreshRegisterHeight: function(_height) {
			$D.setStyle('mcregister-wrap',"height",_height+"px");
			$D.setStyle('MC_standalone_register',"height",_height+"px");
		},

		toggleMCSession: function(_el) {
			var _timeout = document.forms.mclogin_form["TimeoutMinutes"];
			if (_el.checked) {
				_timeout.value = "20160";
			} else {
				_timeout.value = "0";
			}
		},

		isLoggedIn: function() {
			if ($U.readCookie("at") && $U.readCookie("pd")) return true;
			else return false;
		},

		getUserId: function() {
			if (this.isLoggedIn()) {
				var _cookie = $U.readCookie("at").split("&");
				return _cookie[0].replace(/u=/g,"");
			} else {
				return -1;
			}
		},

		searchArray: function(searchObj, searchValue) {
			for (var i=0; i<searchObj.length; i++) {
				if (searchObj[i] == searchValue) return i;
			}
			return -1;
		},

		getThemeHexValue: function(_theme) {
			switch ($S.getVal('colourTheme')) {
				case "pred": return "7b0415";
				case "pblue": return "043c7b";
				case "pblue2": return "0093c6";
				case "pgrey": return "797979";
				default: return "075c8c";
			}
		},
		
		registerUserAction: function (e, o){
			try{
				if (!!window.s_cbc_sitecatalyst && !!CBC.APP.SC && !!CBC.APP.SC.LinkTracker)
					CBC.APP.SC.LinkTracker.registerLinkClick(e,o);
			}catch(e){
				$U.debug(e);
		}
		}
	};
};
