/**
 * @author Nivaria Innova Team
 */
var $jq = jQuery.noConflict();

$jq.extend({
	createNcmClass: function(options){
		return $jq.createNcmSubClass(NcmAbstractComponent,options);
	},
	
	createNcmSubClass: function(superclass,options){
		if(superclass && $jq.isFunction(superclass)){
			function m_extend(Child, Parent) {
			    var F = function(){};
			    F.prototype = Parent.prototype;
			    Child.prototype = new F();
			    Child.prototype.constructor = Child;
			    Child.superclass = Parent.prototype; 
			};
			
			function m_manager(ncmClass){
				ncmClass.instances = null;
				ncmClass.properties = null;
				ncmClass.datatype = null;
				ncmClass.jsp_utils = null;
				ncmClass.language = null;
				ncmClass.pageUrl = null;
				ncmClass.channel = null;
				ncmClass.inPreview = false;
				ncmClass.issueId = null;
				ncmClass.skin = null;
				ncmClass.pageId = null;

				ncmClass.register = function(objectId,json,jsonData) {
					try {
						var aObject = new ncmClass();
						aObject.initialize(objectId,json,jsonData);
						ncmClass.instances[""+objectId] = aObject;
						if(ncm["registeredInstances"]){
							ncm["registeredInstances"].push({id:objectId,object:aObject});
						}
					} catch(mErr){
						ncm.showError("Error registering component instance",mErr,null,ncmClass.inPreview,ncmClass.jsp_utils);
					}	
				};

				ncmClass.getRegistered = function(objectId) {
					return ncmClass.instances[""+objectId];
				};

				ncmClass.get = function(objectId) {
					return ncmClass.getRegistered(objectId);
				};

				ncmClass.initProperties = function(options) {
					var Me = ncmClass;
					var m_initProperties = function(json) {
						if(json["properties"]) {
							$jq.each(json["properties"],function(i,val){
								Me.properties[this.name]=this.value;
							});
						}
					};
					
					ncmClass.properties = {};
					ncmClass.instances = {};
					ncmClass.datatype = options.datatype?options.datatype:null;
					ncmClass.language = options.language?options.language:null;
					ncmClass.jsp_utils = options.jsp_utils?options.jsp_utils:null;
					ncmClass.pageUrl = options.pageUrl?options.pageUrl:null;
					ncmClass.channel = options.channel?options.channel:null;
					ncmClass.inPreview = options.inPreview?options.inPreview:false;
					ncmClass.issueId = options.issueId?options.issueId:null;
					ncmClass.skin = options.skin?options.skin:null;
					try {
						ncmClass.pageId = options.pageId?options.pageId:null;
					} catch(mErr){}
					
					if(options["json"] && options["json"]["properties"]) {
						m_initProperties(options["json"]);
					} else {
						var params = ncm.concat("action=1&dataTypeName=",ncmClass.datatype?ncmClass.datatype:"","&langName=",ncmClass.language?ncmClass.language:"","&pageUrl=",ncmClass.pageUrl?ncmClass.pageUrl:"");
						$jq.ajax({
					    	async: false,
					        type: "GET",
					        url: ncmClass.jsp_utils,
					        data: params,
					        dataType: "json",
					        error: function(request,msg,ex) {
					           ncm.showError(msg,ex,request,Me.inPreview,Me.jsp_utils);
					        },
					        success: function(json) {
								m_initProperties(json);
					        }
					    });	
					}
				};

				ncmClass.getProperty = function(propName) {
					var res = ncmClass.properties[propName];
					if(!res) res="";
					if(typeof(res)==="undefined") res="";
					return res;
				};
			};
			
			var d = new Date();
			this[""+d.getTime()] = function(){
				if(options && options["fields"]){
					var m_fields = ncm.clone(options["fields"]); 
					$jq.extend(this,m_fields);
				}	
			};
			m_extend(this[""+d.getTime()],superclass);
			m_manager(this[""+d.getTime()]);
			if(options && options["prototype"]){
				$jq.extend(this[""+d.getTime()].prototype,options["prototype"]);
			}
			return this[""+d.getTime()];
		} else {
			return $jq.createNcmClass(options);
		}
	},
	
	extendNcmClass: function(ncmclass,options){
		if(ncmclass && $jq.isFunction(ncmclass)){
			if(options && options["fields"]){
				$jq.extend(ncmclass,options["fields"]);
			}
			if(options && options["prototype"]){
				$jq.extend(ncmclass.prototype,options["prototype"]);
			}
		}
	}
});

var ncm = {
	version: "1.0.1",
	isIE6: $jq.browser.msie && !window["XMLHttpRequest"],
	loadedModules: {},
	eventListeners: {},
	customEventsTriggers: {},
	loadedDialogs: {},
	registeredInstances: [],
	/*Custom events definition*/
	customEvents: {
		ncmValueChange: "ncmValueChange",
		ncmScriptsLoaded: "ncmScriptsLoaded",
		ncmBeforeLoadData: "ncmBeforeLoadData",
		ncmAfterLoadData: "ncmAfterLoadData"
	},
	/*JSON constants*/
	SIMPLE_FIELDS_JSO: "simplefields",
	PROPERTIES_JSO: "properties",
	DS_FIELDS_JSO: "dsfields",
	DS_FIELD_PROPERTIES_JSO: "dsfieldproperties",
	QUERY_GROUPBY_FIELDS_JSO: "groupbyfields",
	QUERY_LAYOUTS_JSO: "layouts",
	QUERY_GEOFIELDS_JSO: "geofields",
	QUERY_TOTALS_JSO: "totals",
	QUERY_ORDERBY_FIELDS_JSO: "orderby",
	QUERY_PARAMS_JSO: "params",
	QUERY_SUBCATEGORY_JSO: "subcategory",
	QUERY_FILTER_JSO: "filter",
	QUERY_ITEM_IMAGE: "itemimage",
	SEARCH_FIELDS_ADV: "srchfieldsadv",
	GMAP_MORE_INFO: "gmapmoreinfo",
	GMAP_CUSTOM_CONTROLS: "gmapcustomctrl",
	GMAP_ICON: "gmapicon",
	GMAP_SEARCH: "gmapsearch",
	DT_JSO: "datatype",
	MEDIA_DESCR_FIELDS_JSO: "media_description_fields",
	MEDIA_THUMB_FIELDS_JSO: "media_thumbnail_fields",
	MEDIA_THUMBNAIL_JSO: "media_thumbnail",
	MEDIA_OBJECT_JSO: "media_object",
	MEDIA_DOWNLOAD_JSO: "media_download",
	DS_TYPE_TXT: 0,
	DS_TYPE_DB: 1,
	DS_TYPE_ITEMS: 2,
	DS_TYPE_CATEGORIES: 3,
    DS_TYPE_CATEGORIZE: 4,
    DS_TYPE_CALENDAR: 5,
    DS_TYPE_GDATA_YOUTUBE: 6,
    DS_TYPE_FILESYSTEM: 7,
    passphrase: "Mauris malesuada pretium dui a vulputate",
	/*Load JavaScript by AJAX*/
	load: function(filePath,async,cache,callback,triggerEvent,className) {
		if(ncm.loadedModules[filePath]) return false;
		
		var m_process = function(){
			if(callback) {
	    		if($jq.isFunction(callback)){
	    			callback();
	    		}
	    	}
	    	if(triggerEvent){
	    		ncm.triggerEvent(ncm.customEvents["ncmScriptsLoaded"]+(className?className:""));
	    	}
		};
		
		var isLoaded = true;
		$jq.ajax({
			async: async?async:false,
			cache: cache?cache:false,
			type: "GET",
			url: filePath,
			dataType: "script",
			contentType: "text/javascript",
			error: function(request,msg,ex) {
			   isLoaded = false;		
	           ncm.showError(msg,ex,request);
	        },
	        complete: function(req,status){
	        	if(!req || req.status==200 || req.status==304) {
	        		m_process();
	        	}	
	        }
		});
		ncm.loadedModules[filePath] = isLoaded;
		return isLoaded;
	},
	/*Initialize data type properties*/
	initProperties: function(object,options) {
		var m_initProperties = function(json) {
			if(json.properties) {
				$jq.each(json.properties,function(i,val){
					object.properties[this.name]=this.value;
				});
			}
		};
		
		object.datatype = options.datatype?options.datatype:null;
		object.language = options.language?options.language:null;
		object.jsp_utils = options.jsp_utils?options.jsp_utils:null;
		object.pageUrl = options.pageUrl?options.pageUrl:null;
		object.channel = options.channel?options.channel:null;
		object.inPreview = options.inPreview?options.inPreview:false;
		object.issueId = options.issueId?options.issueId:null;
		object.skin = options.skin?options.skin:null;
		try {
			object.pageId = options.pageId?options.pageId:null;
		} catch(mErr){}
		
		if(options.json && options.json.properties) {
			m_initProperties(options.json);
		} else {
			var params = ncm.concat("action=1&dataTypeName=",object.datatype?object.datatype:"","&langName=",object.language?object.language:"","&pageUrl=",object.pageUrl?object.pageUrl:"");
			$jq.ajax({
		    	async: false,
		        type: "GET",
		        url: object.jsp_utils,
		        data: params,
		        dataType: "json",
		        error: function(request,msg,ex) {
		           ncm.showError(msg,ex,request,object.inPreview,object.jsp_utils);
		        },
		        success: function(json) {
					m_initProperties(json);
		        }
		    });	
		}
	},
	/*Initialize component simple fields*/
	initSimpleFields: function(manager,object,json) {
		var m_initSimpleFields = function(json) {
			if(json.simplefields) {
				$jq.each(json.simplefields,function(i,val){
					object.simplefields[this.name]=this.value;
				});
			}
		};
		
		if(json && json.simplefields) {
			m_initSimpleFields(json);
		} else {
			var jspfile = manager.jsp_utils;
			if(jspfile==null)
				jspfile = manager.getProperty("utils_jsp");
			if(jspfile=="") jspfile= new String("components/components-utils.jsp");
			var params = ncm.concat("action=2&objId=",object.id,"&langName=",manager.language?manager.language:"","&pageUrl=",manager.pageUrl?manager.pageUrl:"","&channel=",manager.channel?manager.channel:"","&issueId=",manager.issueId?manager.issueId:"-1");
			$jq.ajax({
		    	async: false,
		       	type: "GET",
		       	url: jspfile,
		       	data: params,
		       	dataType: "json",
		       	error: function(request,msg,ex) {
		       		ncm.showError(msg,ex,request,manager.inPreview,manager.jsp_utils);
		       	},
		       	success: function(json) {
					m_initSimpleFields(json);
		       	}
		   	});
		}
	},
	/*Initialize events listeners*/
	initEventsListeners: function(manager,object) {
		if(window["jso"+object.id] && window["jso"+object.id]["RELATIONS"]) {
			$jq.each(window["jso"+object.id]["RELATIONS"],function(index,value){
				var m_id = "";
				var m_events = new Array();
				$jq.each(this.simplefields,function(in1,val1){
					if(this.name==="DATAID") {
						m_id = this.value;
					}
					if(this.name==="EVENTS") {
						m_events = this.value;
					}
				}); 
				if(m_id!=="" && m_events.length>0) {
					$jq.each(m_events,function(in2,val2){
						if(!object.eventsListeners[this]){
							object.eventsListeners[this] = new Array();	
						}
						object.eventsListeners[this].push(parseInt(m_id));
					});	
				}
			});
		} else {
			var jspfile = manager.jsp_utils;
			if(jspfile==null)
				jspfile = manager.getProperty("utils_jsp");
			if(jspfile=="") jspfile= new String("components/components-utils.jsp");
			var params = ncm.concat("action=8&objId=",object.id,"&langName=",manager.language?manager.language:"","&pageUrl=",manager.pageUrl?manager.pageUrl:"","&channel=",manager.channel?manager.channel:"","&issueId=",manager.issueId?manager.issueId:"-1");
			$jq.ajax({
		    	async: false,
		       	type: "GET",
		       	url: jspfile,
		       	data: params,
		       	dataType: "json",
		       	error: function(request,msg,ex) {
		       		ncm.showError(msg,ex,request,manager.inPreview,manager.jsp_utils);
		       	},
		       	success: function(json) {
					if(json!=null && json.length>0) {
						$jq.each(json,function(i,val){
							object.eventsListeners[this.event]=this.ids;
						});
					}
		       	}
		   	});
		}
	},
	/*Initialize events triggers (who affects me?)*/
	initEventsTriggers: function(manager,object) {
		var jspfile = manager.jsp_utils;
		if(jspfile==null)
			jspfile = manager.getProperty("utils_jsp");
		if(jspfile=="") jspfile= new String("components/components-utils.jsp");
		var params = ncm.concat("action=9&objId=",object.id,"&pageId=",manager.pageId?manager.pageId:"-1");
		$jq.ajax({
	    	async: false,
	       	type: "GET",
	       	url: jspfile,
	       	data: params,
	       	dataType: "json",
	       	error: function(request,msg,ex) {
	       		ncm.showError(msg,ex,request,manager.inPreview,manager.jsp_utils);
	       	},
	       	success: function(json) {
				if(json!=null && json.length>0) {
					$jq.each(json,function(i,val){
						object.triggersMap[i] = ncm.intval(this);
						object.triggers[""+val]="";
					});
				}
	       	}
	   	});
	},
	/*String concatenation utility function*/
	concat: function() {
		var s = [];
		$jq.each(arguments,function(index,val){
			s.push(val);
		});
		return s.join("");
	},
	/*Clone the JavaScript object*/
	clone: function(jsobject){
		return $jq.evalJSON($jq.compactJSON(jsobject));
	},
	/*Execute one method of given object*/
	exec: function(){
		var p = [];
		var obj = null;
		var m = "";
		$jq.each(arguments,function(index,val){
			switch(index){
				case 0:
					obj = this;
					break;
				case 1:
					m = val;
					break;
				default:
					p.push(this);
					break;
			}
		});
		if(!(obj && m && obj[m] && $jq.isFunction(obj[m]))) return;
		try {
			obj[m].apply(obj,p);
		} catch(mErr){}
	},
	/*Show error utility function*/
	showError: function(msg,ex,request,isPreview,jspfile) {
		var m = ncm.concat(msg,":\n");
	    if(ex) {
	    	m = ncm.concat(m,ex.message?ex.message+"\n":"",ex.fileName?"File: "+ex.fileName+"\n":"",ex.lineNumber?"Line: "+ex.lineNumber+"\n":"",ex.stack?"Stack: "+ex.stack+"\n":"");
	    }
		if(request!=null) {
			m = ncm.concat(m,request.status?request.status+"\n":"",request.statusText?request.statusText+"\n":"");
		}
		if(!jspfile) jspfile = new String("components/components-utils.jsp");
		$jq.post(jspfile,{pageUrl:window.location["href"],errMessage:m});
		if(isPreview) {
			alert(m);	
		}
	},
	/*Open pop-up window utility function*/
	openWindow: function(url) {
	    if ($jq.trim(url)!= "") {
			var w = open(url);
			if(w){
				w.focus();
			}
		}
	},
	/*Binding custom event*/ 
	bindCustomEvent: function(eventName,selector,object,methodName,staticParams) {
		if(!object) return;
		$jq(selector).bind(eventName,function(e,dataIds,params,triggerId){
				if($jq.inArray(object.id,dataIds)==-1) return;
				var triggerIndex = $jq.inArray(triggerId,object.triggersMap);
				if(triggerIndex>-1) {
					object.triggers[""+object.triggersMap[triggerIndex]] = params;
				}
				var p = "";
				for(var i=0;i<object.triggersMap.length;i+=1) {
					var pp = object.triggers[""+object.triggersMap[i]];
					if($jq.trim(""+pp)!="") p+=($jq.trim(p)!=""?"&":"")+pp;				
				}
				if($jq.isFunction(object[methodName]))
					object[methodName](p,true,staticParams);
		});
		ncm.addEventListener(eventName,selector);
	},
	bindCustomEventForSelector: function(eventName,selector,objectId,callback){
		if(!objectId) return;
		if(!ncm.customEventsTriggers[""+objectId]) return;
		$jq(selector).bind(eventName,function(e,params,triggerId){
			if($jq.inArray(triggerId,ncm.customEventsTriggers[""+objectId])==-1) return;
			if(callback){
				if($jq.isFunction(callback)){
					callback(params);
				}
			}
		});
		ncm.addEventListener(eventName,selector);
	},
	/*Triggering custom event*/
	triggerCustomEvent: function(eventName,object,params) {
		if(!object) return;
		if(object.eventsListeners[eventName]!=null){
			ncm.triggerEvent(eventName,[object.eventsListeners[eventName],params,object.id]);	
		}
	},
	/*Adding custom event listener*/
	addEventListener: function(eventName,selector) {
		if(ncm.eventListeners[eventName]) {
			if($jq.inArray(selector,ncm.eventListeners[eventName])===-1) {
				ncm.eventListeners[eventName].push(selector);
			}
		} else {
			ncm.eventListeners[eventName] = new Array(selector);
		}
	},
	/*Getting custom event listeners*/
	getEventListeners: function(eventName) {
		return ncm.eventListeners[eventName]?ncm.eventListeners[eventName]:null; 
	},
	/*Getting selector for custom event listeners*/
	getEventListenersSelector: function(eventName) {
		var arr = ncm.getEventListeners(eventName);
		return arr?arr.join(","):"";
	},
	/*Trigger event*/
	triggerEvent: function(eventName,arrParams) {
		var s = ncm.getEventListenersSelector(eventName);
		if(s!=="") {
			$jq(s).trigger(eventName,arrParams);
		}
	},
	/*Decode URL parameters utility function*/
	decodeParams: function(params) {
		return decodeURIComponent(params).replace(/\+/ig," ");
	}, 
	/*Getting parameters from URL*/
	getParametersFromUrl: function() {
		return ncm.getParametersFromUrlAsObject();
	},
	getParametersFromUrlAsString: function(separator) {
		var res = "";
		if(window.location["search"]) {
			var qparams = window.location["search"].replace(/\?/,"");
			var initParams = qparams.split("&");
			if(initParams!=null && initParams.length>0) {
				$jq.each(initParams,function(i,val){
					var pos = this.indexOf("=");
					var arr = [];
					if(pos>0) {
						arr[0] = this.substr(0,pos);
						arr[1] = this.substr(pos+1);
					} else {
						arr[0] = this;
						arr[1] = "";
					}
					res = ncm.concat(res,i===0?"":separator,arr[0],separator,arr[1]);
				});
			}	
		}
		return res;
	},
	getParametersFromUrlAsObject: function() {
		var res = {};
		if(window.location["search"]) {
			var qparams = window.location["search"].replace(/\?/,"");
			res = ncm.transformParamsStringToObject(qparams);
		}
		return res;
	},
	transformParamsStringToObject: function(strParams) {
		var res = {};
		var initParams = strParams.split("&");
		if(initParams!=null && initParams.length>0) {
			$jq.each(initParams,function(i,val){
				var pos = this.indexOf("=");
				var arr = [];
				if(pos>0) {
					arr[0] = ncm.decodeParams(this.substr(0,pos));
					arr[1] = ncm.decodeParams(this.substr(pos+1));
				} else {
					arr[0] = ncm.decodeParams(this);
					arr[1] = "";
				}
				res[arr[0]] = arr[1];
			});
		}
		return res;
	},
	getParametersNamesFromString: function(strParams){
		var res = [];
		var initParams = strParams.split("&");
		if(initParams!=null && initParams.length>0) {
			$jq.each(initParams,function(i,val){
				var pos = this.indexOf("=");
				var p = null;
				if(pos>0) {
					p = ncm.decodeParams(this.substr(0,pos));
				} else {
					p = ncm.decodeParams(this);
				}
				if(p) res.push(p);
			});
		}
		return res;
	},
	/*Google Analytics utility function*/
	gatcLinks: function(selector,pageName) {
		$jq("a",selector).click(function(){
			if(typeof(pageTracker)==="undefined") return;
			if(!pageTracker) return;
			var virtPath = "/"+pageName;
			var href = this.getAttribute("href");
			if(!href) return;
			var isFile = href?(href.indexOf(".doc")!=-1 || href.indexOf(".xsl")!=-1 || href.indexOf(".pdf")!=-1 || href.indexOf(".ppt")!=-1):false; 
			var targ = this.getAttribute("target");
			var isExt = targ?targ=="_blank":false;
			var title = this.getAttribute("title");
			virtPath += "/"+(isFile?"download":(isExt?"external_link":"internal_link"));
			virtPath += "/"+(title?title:href);
			pageTracker._trackPageview(virtPath);
		});
	},
	gatcLinkInfo: function(domElem, pageName){
		if(!domElem) return null;
		if(!domElem.tagName) return null;
		if(domElem.tagName.toUpperCase()!=="A") return null;
		var jqA = $jq(domElem);
		if(jqA.attr("rel")==="nofollow") return null;
		var href = jqA.attr("href");
		if(!href) return null;
		if(href==="" || href==="#" || href==="noscript.html") return null;
		var title = jqA.attr("title")?jqA.attr("title"):"no title";
		title = ncm.concat(pageName,": ",title);
		href = href.split("?")[0];
		var filePattern = /\.(pdf|doc|rtf|zip|rar|xls|docx|ppt|pps|xlsx)$/i;
		var imagePattern = /\.(jpg|gif|png|jpeg)$/i;
		var extLinkPattern = new RegExp("^(http|https):\/\/","i");
		var res = [];
		if(filePattern.test(href)){
			res.push("1");
			res.push(href.substr(href.lastIndexOf(".")+1));
			res.push(href);
		} else if(imagePattern.test(href)){
			res.push("2");
			res.push(title);
			res.push(href);
		} else if(extLinkPattern.test(href)){
			res.push("3");
			res.push(title);
			res.push(href);
		} else {
			res.push("-1");
			res.push(title);
			res.push(href);
		}
		return res;
	},
	/*Functions for cookies*/
	createCookie: function(name,value,days) {
		var expires = "";
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			expires = ncm.concat("; expires=",date.toGMTString());
		}
		document.cookie = ncm.concat(name,"=",value,expires,"; path=/");
	},
	readCookie: function (name) {
		var res = null;
		var nameEQ = ncm.concat(name,"=");
		var ca = document.cookie.split(';');
		$jq.each(ca,function(i,val){
			val = $jq.trim(val);
			if (val.indexOf(nameEQ)==0) {
				res = val.substring(nameEQ.length,val.length);
				return false;
			}	
		});
		return res;
	},
	eraseCookie: function(name) {
		createCookie(name,"",-1);
	},
	/*Dialogs (based on jQuery dialog plug-in)*/
	showDialog: function(objId,message,append) {
		var jqD = $jq(ncm.concat("div#dialog",objId));
		if(!ncm.loadedDialogs[""+objId]) {
			ncm.loadedDialogs[""+objId] = jqD.html(message).dialog().parent();	
		} else {
			if(append) {
				jqD.append(message);
			} else {
				jqD.html(message);	
			}
		}
		if(ncm.loadedDialogs[""+objId].length>0) {
			var x = ($jq(window).width()/2) - (ncm.loadedDialogs[""+objId].width()/2);
			var y = ncm.loadedDialogs[""+objId].offset().top;
			ncm.loadedDialogs[""+objId].css({top:y+"px",left:x+"px"}).show();			
		}
	},
	hideDialog: function(objId) {
		$jq(ncm.concat("div#dialog",objId)).html("");
		if(ncm.loadedDialogs[""+objId]) {
			ncm.loadedDialogs[""+objId].hide();
		}
	},
	/*Integer value utility function*/
	intval: function(v) {
		v = parseInt(v);
	    return isNaN(v) ? 0 : v;
	},
	/*Getting random banner utility function*/
	getRandomBanner: function(objectId,fieldName,pageUrl,jsp,selector) {
		var params = {
				objectId: objectId,
				objectField: fieldName,
				pageUrl: pageUrl
		};
		$jq.getJSON(jsp,params,function(json){
			if(json && json.image) {
				$jq(selector).css("background-image",ncm.concat("url","(",json.image,")"));				
			}
		});
	},
	/*Check the query detail step*/
	isDetailsStep: function() {
		var p = window.location["search"].replace(/\?/,"");
		return p.indexOf("ID=")!==-1 || p.indexOf("PRDID=")!==-1 || p.indexOf("PROID=")!==-1;
	},
	/*Component constructor parameters*/
	getComponentConstructorParams: function(object,manager,withjso) {
		var res = ncm.concat("objId=",object.id,"&inPreview=",manager.inPreview?manager.inPreview:false,"&language=",manager.language?manager.language:"","&pageUrl=",manager.pageUrl?manager.pageUrl:"","&channel=",manager.channel?manager.channel:"","&issueId=",manager.issueId?manager.issueId:"","&className=",manager.name?manager.name:"","&pageId=",manager.pageId?manager.pageId:"0");
		if(withjso) {
			if(window["jso"+object.id]) {
				res = ncm.concat(res,"&jso=",$jq.compactJSON(window["jso"+object.id]));
			}
		}
		return res;
	},
	getComponentConstructorParamsObject: function(object,manager,withjso) {
		var res = {
			objId : object.id,
			inPreview: manager.inPreview?manager.inPreview:false,
			language: manager.language?manager.language:"",
			pageUrl: manager.pageUrl?manager.pageUrl:"",
			channel: manager.channel?manager.channel:"",
			issueId: manager.issueId?manager.issueId:"",
			className: manager.name?manager.name:"",
			pageId: manager.pageId?manager.pageId:"0"       
		};
		if(withjso) {
			if(window["jso"+object.id]) {
				$jq.extend(res,{jso:$jq.compactJSON(window["jso"+object.id])});
			}
		}
		return res;
	},
	/*Serialize form as an object*/
	serializeToObject: function(selector) {
		var sa =  $jq(selector).serializeArray();
		return ncm.serializeJSONToObject(sa)
	},
	serializeToString: function(selector){
		var sa =  $jq(selector).serializeArray();
		var res = "";
		$jq.each(sa,function(i,p){
			if(p.value) {
				if(p.value instanceof Array){
					$jq.each(p.value,function(k,val){
						if(val){
							res = ncm.concat(res,res!=""?"&":"",p.name,"=",val.replace(/\&nbsp;/ig," "));
						}	
					});
				} else {
					res = ncm.concat(res,res!=""?"&":"",p.name,"=",p.value.replace(/\&nbsp;/ig," "));
				}	
			}
		});
		return res;
	},
	/*Serialize JSON Array to object*/
	serializeJSONToObject: function(json,withEmptyVals){
		var sp = {};
		$jq.each(json,function(i,p){
			if(p.value || withEmptyVals) {
				sp[p.name] = p.value?p.value:"";	
			}
		});
		return sp;
	},
	/*Assign events for pager*/
	setPagerEvents: function(object,selector){
		if(!object) return;
		if(!selector) return;
		/*Initialize events for items per page*/
		$jq("div.pager select.list-items-per-page",selector).change(function(){
			ncm.exec(object,"refresh",this.value);
		});
		/*Initialize events for pager*/
		var jqPgLis = $jq("ul.list-pages li",selector);
		var totalPg = ncm.intval($jq(ncm.concat("#autopager-total-",object.id)).val());
		if(totalPg===0) totalPg = jqPgLis.length-2;
		var currPg = object.getRequestParam(ncm.concat(object.getPrefix(),"page"));
		if(currPg==="") currPg="0";
		jqPgLis.each(function(index){
			if(index===0){
				$jq("a",this).click(function(){
					ncm.exec(object,"gotoPage",parseInt(currPg)>0?parseInt(currPg)-1:0,selector);
					return false;
				}).keypress(function(){
					ncm.exec(object,"gotoPage",parseInt(currPg)>0?parseInt(currPg)-1:0,selector);
					return false;
				});
			} else if(index===jqPgLis.length-1){
				$jq("a",this).click(function(){
					ncm.exec(object,"gotoPage",parseInt(currPg)<totalPg-1?parseInt(currPg)+1:totalPg-1,selector);
					return false;
				}).keypress(function(){
					ncm.exec(object,"gotoPage",parseInt(currPg)<totalPg-1?parseInt(currPg)+1:totalPg-1,selector);
					return false;
				});
			} else {
				$jq("a",this).click(function(){
					var pgg = ncm.intval($jq(this).html())-1;
					if(pgg===-1) pgg=index-1;
					if(pgg!==parseInt(currPg)){
						ncm.exec(object,"gotoPage",pgg,selector);
					}	
					return false;
				}).keypress(function(){
					var pgg = ncm.intval($jq(this).html())-1;
					if(pgg===-1) pgg=index-1;
					if(pgg!==parseInt(currPg)){
						ncm.exec(object,"gotoPage",pgg,selector);
					}	
					return false;
				});
			}
		});
	},
	saveSessionStateInHistory: function(){
		if(ncm["registeredInstances"] && window["dhtmlHistory"]){
			var objStates = [];
			$jq.each(ncm["registeredInstances"],function(ind,val){
				if(this["id"] && this["object"] && this["object"]["requestParams"]){
					var reqParams = ncm.clone(this["object"]["requestParams"]);
					reqParams.push({"name":"resetParams","value":"true"});
					objStates.push({id:this["id"],params:reqParams});
				}
			});
			var objStatesString = $jq.toJSON(objStates);
			var objHash = Crypto.MD5(objStatesString);
			var objCrypt = Crypto.AES.encrypt(objStatesString,ncm.passphrase);
			window["dhtmlHistory"].add(objHash,objCrypt);
		}	
	},
	restoreSavedSessionState: function(hash,crypt){
		if(hash && crypt){
			var objStatesString = Crypto.AES.decrypt(crypt,ncm.passphrase);
			if(objStatesString){
				var objStates = $jq.evalJSON(objStatesString);
				if(objStates && $jq.isArray(objStates)){
					$jq.each(objStates,function(ind,val){
						var obj = ncm.getInstance(this["id"]);
						if(obj && obj["restoreState"] && $jq.isFunction(obj["restoreState"]) && this["params"]){
							obj["restoreState"]($jq.param(ncm.serializeJSONToObject(this["params"])));
						}
					});
				}
			}
		} 
	},
	getInstance: function(objId){
		var res = null;
		if(ncm["registeredInstances"]){
			$jq.each(ncm["registeredInstances"],function(ind,val){
				if(this["id"]===objId){
					res = this["object"];
					return false;
				}
			});
		}
		return res;
	}
};

function NcmAbstractComponent() {
}

NcmAbstractComponent.prototype = {
	initialize: function(objectId,json,jsonData) {
		this.id = objectId;
		/*Getting component simple fields values*/
		this.initSimpleFields(json);
		/*Initialize events listeners*/
		if(this["eventsListeners"]){
			this.initEventsListeners();
		}	
		/*Initialize events triggers*/
		if(this["triggers"] && this["triggersMap"]){
			this.initEventsTriggers();
		}	
		/*Initialize component*/
		this.initComponent(jsonData);
	},
	
	initComponent: function(jsonData) {
	},
	
	/*Initialize component simple fields*/
	initSimpleFields: function(json) {
		var Me = this;
		var m_initSimpleFields = function(json) {
			if(json["simplefields"]) {
				$jq.each(json["simplefields"],function(i,val){
					Me.simplefields[this.name]=this.value;
				});
			}
		};
		
		if(json && json["simplefields"]) {
			m_initSimpleFields(json);
		} else {
			var jspfile = this.constructor.jsp_utils;
			if(!jspfile) jspfile= new String("components/components-utils.jsp");
			var params = ncm.concat("action=2&objId=",this.id,"&langName=",this.constructor.language?this.constructor.language:"","&pageUrl=",this.constructor.pageUrl?this.constructor.pageUrl:"","&channel=",this.constructor.channel?this.constructor.channel:"","&issueId=",this.constructor.issueId?this.constructor.issueId:"-1");
			$jq.ajax({
		    	async: false,
		       	type: "GET",
		       	url: jspfile,
		       	data: params,
		       	dataType: "json",
		       	error: function(request,msg,ex) {
		       		ncm.showError(msg,ex,request,Me.constructor.inPreview,Me.constructor.jsp_utils);
		       	},
		       	success: function(json) {
					m_initSimpleFields(json);
		       	}
		   	});
		}
	},
	
	/*Initialize events listeners*/
	initEventsListeners: function() {
		var Me = this;
		if(window["jso"+this.id] && window["jso"+this.id]["RELATIONS"]) {
			$jq.each(window["jso"+this.id]["RELATIONS"],function(index,value){
				var m_id = "";
				var m_events = [];
				$jq.each(this.simplefields,function(in1,val1){
					if(this.name==="DATAID") {
						m_id = this.value;
					}
					if(this.name==="EVENTS") {
						m_events = this.value;
					}
				}); 
				if(m_id!=="" && m_events.length>0) {
					$jq.each(m_events,function(in2,val2){
						if(!Me.eventsListeners[this]){
							Me.eventsListeners[this] = [];	
						}
						if(!Me.eventsListenersAdv[this]){
							Me.eventsListenersAdv[this] = {};	
						}
						Me.eventsListeners[this].push(parseInt(m_id));
						Me.eventsListenersAdv[this][parseInt(m_id)] = value;
					});	
				}
			});
		} else {
			var jspfile = this.constructor.jsp_utils;
			if(!jspfile) jspfile= new String("components/components-utils.jsp");
			var params = ncm.concat("action=8&objId=",this.id,"&langName=",this.constructor.language?this.constructor.language:"","&pageUrl=",this.constructor.pageUrl?this.constructor.pageUrl:"","&channel=",this.constructor.channel?this.constructor.channel:"","&issueId=",this.constructor.issueId?this.constructor.issueId:"-1");
			$jq.ajax({
		    	async: false,
		       	type: "GET",
		       	url: jspfile,
		       	data: params,
		       	dataType: "json",
		       	error: function(request,msg,ex) {
		       		ncm.showError(msg,ex,request,Me.constructor.inPreview,Me.constructor.jsp_utils);
		       	},
		       	success: function(json) {
					if(json!=null && json.length>0) {
						$jq.each(json,function(i,val){
							Me.eventsListeners[this.event]=this.ids;
						});
					}
		       	}
		   	});
		}
	},
	
	/*Initialize events triggers (who affects me?)*/
	initEventsTriggers: function() {
		var Me = this;
		if(ncm.customEventsTriggers){
			if(ncm.customEventsTriggers[""+this.id]){
				this.triggersMap = ncm.customEventsTriggers[""+this.id];
				$jq.each(this.triggersMap,function(i,val){
					Me.triggers[""+val]="";
				});
			}
		} else {
			var jspfile = this.constructor.jsp_utils;
			if(!jspfile) jspfile= new String("components/components-utils.jsp");
			var params = ncm.concat("action=9&objId=",this.id,"&pageId=",this.constructor.pageId?this.constructor.pageId:"-1");
			$jq.ajax({
		    	async: false,
		       	type: "GET",
		       	url: jspfile,
		       	data: params,
		       	dataType: "json",
		       	error: function(request,msg,ex) {
		       		ncm.showError(msg,ex,request,Me.constructor.inPreview,Me.constructor.jsp_utils);
		       	},
		       	success: function(json) {
					if(json!=null && json.length>0) {
						$jq.each(json,function(i,val){
							Me.triggersMap[i] = ncm.intval(this);
							Me.triggers[""+val]="";
						});
					}
		       	}
		   	});
		}	
	},
	
	/*Getting request parameter*/
	getRequestParam: function(pname){
		var res = "";
		if(this["requestParams"]){
			$jq.each(this["requestParams"],function(index,val){
				if(this.name===pname){
					res = this.value;
					return false;
				}
			});
		}
		return res;
	},
	
	/*Getting names of all request parameters*/
	getRequestParamsNames: function(){
		var res = [];
		if(this["requestParams"]){
			$jq.each(this["requestParams"],function(index,val){
				res.push(this.name);
			});
		}
		return res;
	},
	
	/*Setting request parameter*/
	setRequestParam: function(pname,pvalue,append){
		if(!this["requestParams"]){
			this["requestParams"] = [];
		}
		var pfound = false;
		$jq.each(this["requestParams"],function(index,val){
			if(this.name===pname){
				/* check some special parameters */
				if (pname.indexOf("CATID") != -1) {
					append = false;
				}
				if(!append){
					this.value = pvalue;
				} else {
					var m_vals = this.value;
					if(!(m_vals instanceof Array)){
						this.value = new Array();
						this.value.push(m_vals);
						this.value.push(pvalue);
					} else {
						this.value.push(pvalue);
					}
				}	
				pfound = true;
				return false;
			}
		});
		if(!pfound){
			this["requestParams"].push({"name":pname,"value":pvalue});
		}
	},
	
	updateRequestParams: function(strParams) {
		var Me = this;
		var initParams = strParams.split("&");
		if ($jq.inArray("resetParams", initParams)) {
			this["requestParams"] = [];
		}
		if (initParams && initParams.length>0) {
			var m_cleaned = [];
			$jq.each(initParams,function(i,val){
				var pos = this.indexOf("=");
				var arr = [];
				if (pos > 0) {
					arr[0] = ncm.decodeParams(this.substr(0,pos));
					arr[1] = ncm.decodeParams(this.substr(pos+1));
				} else {
					arr[0] = ncm.decodeParams(this);
					arr[1] = "";
				}
				if ($jq.inArray(arr[0], m_cleaned) === -1) {					
					Me.setRequestParam(arr[0],arr[1],false);
					m_cleaned.push(arr[0]);
				} else {
					/* if the parameter has been already inserted append a new one */
					Me.setRequestParam(arr[0],arr[1],true);
				}
			});
		}
	},
	
	/*Initialize request parameters from form element */
	initializeRequestParams: function(formId){
		if(!formId) formId=ncm.concat("initial-request-",this.id);
		var form = document.getElementById(formId);
		if(form){
			var strParams = $jq(form).serialize();
			this.updateRequestParams(strParams);
		}
	},
	
	/*Getting data source prefix*/
	getPrefix: function(dsField) {
		var datasourceField = dsField?dsField:"DATASOURCE";
		return this.simplefields[datasourceField]?ncm.concat("DS",this.simplefields[datasourceField],"."):"";
	},
	
	/*Getting data source prefixes for all listeners*/
	getListenersPrefixes: function(eventName){
		var res = [];
		if(this["eventsListeners"]){
			if(this["eventsListeners"][eventName]){
				if(this["eventsListeners"][eventName].length>0){
					$jq.each(this["eventsListeners"][eventName],function(ind,val){
						if(window[ncm.concat("jso",val)]){
							if(window[ncm.concat("jso",val)][ncm.SIMPLE_FIELDS_JSO]){
								$jq.each(window[ncm.concat("jso",val)][ncm.SIMPLE_FIELDS_JSO],function(indj,valj){
									if(this.name==="DATASOURCE"){
										var m_prefix = ncm.concat("DS",this.value,".");
										if($jq.inArray(m_prefix,res)===-1){
											res.push(m_prefix);
										}
										return false;
									}
								});
							}
						}
					});
				}
			}
		}
		return res;
	},
	
	getAjaxProgress: function(){
		return ncm.concat("<","div class=\"ajax-progress\"",">","<","img src=\"",this.constructor.getProperty("img_ajax_progress"),"\" title=\"\" alt=\"\" \/",">",this.constructor.getProperty("lang_loading"),"<","\/div",">");
	},
	
	processKeyParams: function(m_params) {
		var result = "";
		var jspfile = this.constructor.getProperty("jsp_detailrelations");
		if (!jspfile)
			jspfile = "components/queries/processobjectkeyrelations.jsp";
		var keyParams = m_params.split("&");
		var keyParamsJSON = [];
		$jq.each(keyParams, function(i, param) {
			keyParamsJSON.push(param);
		});
		var params = "keyParam="+$jq.toJSON(keyParamsJSON);
		params += "&dsId="+this.simplefields["DATASOURCE"];
		params += "&language="+this.constructor.language;
		params += "&inPreview="+this.constructor.inPreview;
		params += "&eventsListeners="+$jq.toJSON(this.eventsListeners);
		params += "&eventsListenersAdv="+$jq.toJSON(this.eventsListenersAdv);
		$jq.ajax({
			async:false,
			type:"POST",
			dataType:"json",
			url:jspfile,
			data:params,
			success:function(res) {
				if (res != null && res.params != null) {
					for (var i = 0; i < res.params.length; i++) {
						if (res.params[i] != null && res.params[i].keys != null) {
							var prefix = res.params[i].prefix;
							for (var j = 0; j < res.params[i].keys.length; j++) {
								var key = res.params[i].keys[j].key;
								var value = res.params[i].keys[j].value;
								result += "&"+prefix+key+"="+value;
							}
						}
					}
				}					
			}
		});
		return "resetParams=1"+result;
	},
	
	refresh: function(itpp) {
		this.setRequestParam(ncm.concat(this.getPrefix(),"page"),"0");
		this.setRequestParam(ncm.concat(this.getPrefix(),"itpp"),ncm.concat("",itpp));
		ncm.exec(this,"loadData");
	},
	
	gotoPage: function(ppage,selector){
		if(ppage<0) return;
		var totalPg = ncm.intval($jq(ncm.concat("#autopager-total-",this.id)).val());
		if(totalPg===0) totalPg=$jq("ul.list-pages li",selector).length-2;
		if(ppage>totalPg-1) return;
		this.setRequestParam(ncm.concat(this.getPrefix(),"page"),ncm.concat("",ppage));
		ncm.exec(this,"loadData");
	},
	
	restoreState: function(params){
		if(this["loadData"] && $jq.isFunction(this["loadData"])){
			this.updateRequestParams(params);
			this.loadData();
		}	
	}
};
