/**
* @author Nivaria Innova Team
*/
var $jq = jQuery.noConflict();
//Enables for all serialization
$jq.ajaxSettings.traditional = true;

$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) {
               var aObject = new ncmClass();
               aObject.initialize(objectId,json,jsonData);
               ncmClass.instances[""+objectId] = aObject;
            }

            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"]);
         }
      }
   }
});
/** @id linkEvents */
$jq.fn.linkEvents = function(callback){
    if(callback && $jq.isFunction(callback)){
        this.click(callback).keypress(callback);
    }
};
/** @id liveLinkEvents */
$jq.fn.liveLinkEvents = function(callback){
    if(callback && $jq.isFunction(callback)){
        this.live("click",callback).live("keypress",callback);
    }
};
var ncm = {
   version: "1.0.1",
   isIE6: $jq.browser.msie && $jq.browser.version.substr(0,1)==='6',
   loadedModules: {},
   eventListeners: {},
   customEventsTriggers: {},
   loadedDialogs: {},
   //Custom events definition
   customEvents: {
      ncmValueChange: "ncmValueChange",
      ncmScriptsLoaded: "ncmScriptsLoaded",
      ncmBeforeLoadData: "ncmBeforeLoadData",
      ncmAfterLoadData: "ncmAfterLoadData",
      ncmRollover: "ncmRollover",
      ncmSuccess: "ncmSuccess",
      ncmError: "ncmError"
   },
   //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",
   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,
   //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.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) {
           if(ncm.customEventsTriggers && ncm.customEventsTriggers[""+object.id]){
                  object.triggersMap = ncm.customEventsTriggers[""+object.id];
                  $jq.each(object.triggersMap,function(i,val){
                        object.triggers[""+val]="";
                  });
            } 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=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(jQueryEvent,params,triggerId,e){
            if($jq.inArray(triggerId,ncm.customEventsTriggers[""+objectId])==-1) return;
            if(callback){
               if($jq.isFunction(callback)){
                  callback(params,e);
               }
            }
         });
         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 params.replace(/%3A/ig,":").replace(/%2F/ig,"\/");
   }, 
   //Getting parameters from url
   getParametersFromUrl: function() {
      return ncm.getParametersFromUrlAsObject();
   },
   getParametersFromUrlAsString: function(separator) {
      var res = "";
        if(window["originalRequestString"] || window.location["search"]) {
            var qparams = window["originalRequestString"]?window["originalRequestString"]: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["originalRequestString"] || window.location["search"]) {
            var qparams = window["originalRequestString"]?window["originalRequestString"]: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==="#") 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 = /^(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) {
       var re = new RegExp("^0[1-9]");
       if(re.test(v) && v["substr"]){
        v = v.substr(1);
       }
       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","url("+json.image+")");            
         }
      });
   },
   //Check the query detail step
   isDetailsStep: function() {
        var p = window["originalRequestString"]?window["originalRequestString"]: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)
   },
   //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;
   },
   serializeDOMElement: function(elemId){
        var res = "";
        if(elemId.charAt(0)==="#"){
            elemId = elemId.substr(1);
        }
        var form = document.getElementById(elemId);
        if(form){
            if(form.tagName==="FORM" || form.tagName==="form"){
                res = $jq(form).serialize();
            } else {
                $jq("body").append(ncm.concat("<form id=\"tmp-",elemId,"\" style=\"visibility:hidden;\"><\/form>"));
                var jqForm = $jq(ncm.concat("#tmp-",elemId));
                jqForm.html($jq(form).clone());
                res = jqForm.serialize();
                jqForm.remove();
            }    
        }
        return res;
    },
    /*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).removeAttr("disabled").change(function(){
            ncm.exec(object,"refresh",this.value);
        });
        /*Initialize events for go to page*/
        $jq("div.pager select.list-go-to-page",selector).removeAttr("disabled").change(function(){
            ncm.exec(object,"gotoPage",ncm.intval(this.value),selector);
        });
        /*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).linkEvents(function(){
                    ncm.exec(object,"gotoPage",parseInt(currPg)>0?parseInt(currPg)-1:0,selector);
                    return false;
                });
            } else if(index===jqPgLis.length-1){
                $jq("a",this).linkEvents(function(){
                    ncm.exec(object,"gotoPage",parseInt(currPg)<totalPg-1?parseInt(currPg)+1:totalPg-1,selector);
                    return false;
                });
            } else {
                $jq("a",this).linkEvents(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;
                });
            }
        });
    },
    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;
    },
    /*Date utilities*/
    dateUtil: {
        checkDateCorrect: function(dd,mm,yyyy) {
            var day=0,month=0,year=0,res=true;
            try {
                year = ncm.intval(yyyy);
                month = ncm.intval(mm.charAt(0)==="0"?mm.substr(1):mm);
                day = ncm.intval(dd.charAt(0)==="0"?dd.substr(1):dd);        
            } catch(mErr) {
                res = false;
            }         
            if(res) {
                if ((day<1 || day>31) || (month<1 || month>12)  || !year)
                    res = false;
                if (day > ncm.dateUtil.getMaxDays(month,year))
                    res = false;
            }
            return res;
        },
        getMaxDays: function(month,year) {
            var monthdays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
            if(month==2) {
                if(ncm.dateUtil.checkLeapYear(year)){
                    monthdays[1]=29;
                } else {
                    monthdays[1]=28;
                }    
            }
            if(month<1 || month>12){
                return -1;
            } else {
                return monthdays[month-1];
            }    
        },
        checkLeapYear: function (yyyy) {
            if(yyyy%4===0 && (yyyy%100!==0 || yyyy%400===0)){ 
                   return true;
            } else {
                return false;
            }    
        },
        checkLinkedDays: function (fieldId) {
            var elem = document.getElementById(fieldId);
            var elemD = document.getElementById(fieldId+"_DAY");
            var elemM = document.getElementById(fieldId+"_MONTH");
            var elemY = document.getElementById(fieldId+"_YEAR");
            if(elemD!=null && elemM!=null && elemY!=null) {
                if($jq(elemD).val()!="" && $jq(elemM).val()!="" && $jq(elemY).val().length==4) {
                    var daysInMonth = 32 - new Date($jq(elemY).val(),$jq(elemM).val()-1,32).getDate(); 
                    $jq("option",elemD).attr('disabled',''); 
                    $jq("option:gt("+daysInMonth+")",elemD).attr('disabled', 'disabled'); 
                    if ($jq(elemD).val() > daysInMonth) { 
                        $jq(elemD).val(daysInMonth); 
                    }
                    $jq(elem).val($jq(elemD).val()+"/"+$jq(elemM).val()+"/"+$jq(elemY).val());    
                } else {
                    $jq(elem).val("");
                }
            }
        },
        formDateValue: function(frm,fldname) {
               var dd="",mm="",yyyy="",res="",date = new Date();
            frm.find(":input[name='"+fldname+"_DAY']").each(function(){
                dd=$jq(this).val();
            }).end().find(":input[name='"+fldname+"_MONTH']").each(function(){
                mm=$jq(this).val();
            }).end().find(":input[name='"+fldname+"_YEAR']").each(function(){
                yyyy=$jq(this).val();
            });
            if(dd==="" && mm==="" && yyyy==="") return res;
               if(mm && !yyyy) {
                   yyyy = ""+date.getFullYear();
               }
               if(!mm && yyyy) {
                   mm = (date.getMonth()<9?"0":"")+(date.getMonth()+1);
               }
            if(ncm.dateUtil.checkDateCorrect(dd,mm,yyyy)) {
                   res=dd+"/"+mm+"/"+yyyy;
               } else {
                res = "#error#";
            }
               return res;
        }
    },
    
    getPublishPath: function(){
        var res = "";
        if(window["page_options"] && window["page_options"]["publishPath"]){
            res = window["page_options"]["publishPath"];
            res = res.substr(0,res.length-1);
        }
        return res;
    }   
};

function NcmAbstractComponent() {
}

NcmAbstractComponent.prototype = {
    initialize: function(objectId,json,jsonData) {
        this.id = objectId;
        /*Getting component simple fields values*/
        this.initSimpleFields(json);
        /*Getting component complex fields values*/
        this.initComplexFields(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 component complex fields*/
    initComplexFields: function(json) {
        var Me = this;
        try {
            if(json && json["complexfields"]) {
                if(json["complexfields"]) {
                    $jq.each(json["complexfields"],function(i,val1){
                        var fieldVals = [];
                        $jq.each(this.values,function(j,val2){
                            var fieldMap = {};
                            if (this.simplefields) {
                                $jq.each(this.simplefields,function(k,val3){
                                    fieldMap[this.name]=this.value;
                                });
                            }
                            fieldVals.push(fieldMap);
                        });
                        Me.complexfields[this.name]=fieldVals.length>1?fieldVals:(fieldVals.length===1?fieldVals[0]:{});
                    });
                }
            }
        } catch (Err) {}
    },
    
    /*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=1", initParams)!==-1) {
            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);
                }
            });
        }
        this.setRequestParam("jsdisabled","0",false);
    },
    
    /*Initialize request parameters from form element */
    initializeRequestParams: function(formId){
        if(!formId) formId=ncm.concat("initial-request-",this.id);
        var strParams = ncm.serializeDOMElement(formId);
        if(strParams){
            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) {
              if($jq.trim(param)!==""){
                  keyParamsJSON.push(param);
              }
        });
        var params = ncm.concat("keyParam=",$jq.toJSON(keyParamsJSON),"&dsId=",this.simplefields["DATASOURCE"],"&language=",this.constructor.language,"&inPreview=",this.constructor.inPreview,"&eventsListeners=",$jq.toJSON(this.eventsListeners),"&eventsListenersAdv=",$jq.toJSON(this.eventsListenersAdv));
        var included = [];
        $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+=1) {
                                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+=1) {
                                            var key = res.params[i].keys[j].key;
                                            var value = res.params[i].keys[j].value;
                                            var onepair = ncm.concat(prefix,key,"=",value);
                                            if($jq.inArray(onepair,included)===-1){
                                                  result = ncm.concat(result,"&",onepair);
                                                  included.push(onepair);
                                            }      
                                      }
                                }
                          }
                    }                              
              }
        });
        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 && this["totalPages"]) totalPg = ncm.intval(this["totalPages"]);
        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();
        }    
    },
    
    getHiddenInputs: function(aExclude){
        var res = "";
        if(this["requestParams"]){
            $jq.each(this["requestParams"],function(i,p){
                if(p.value && $jq.inArray(p.name,aExclude?aExclude:[])===-1) {
                    if(p.value instanceof Array){
                        $jq.each(p.value,function(j,v){
                            res = ncm.concat(res,"<","input type=\"hidden\" name=\"",p.name,"\" value=\"",v,"\""," \/",">\n");
                        });
                    } else {
                        res = ncm.concat(res,"<","input type=\"hidden\" name=\"",p.name,"\" value=\"",p.value,"\""," \/",">\n");
                    }
                }
            });
        }
        return res;
    },
    
    getComplexFieldArray: function(fieldName){
        var res = [];
        var jso = window[ncm.concat("jso",this.id)]; 
        if(jso && jso[ncm.COMPLEX_FIELDS_JSO] && jso[ncm.COMPLEX_FIELDS_JSO].length>0){
            $jq.each(jso[ncm.COMPLEX_FIELDS_JSO],function(ind,val){
                if(this.name===fieldName){
                    res = this.values;
                }
            });
        }
        return res;
    },
    
    getComplexField: function(fieldName, pos){
        if(!pos) pos=0;
        var res = null;
        var arr = this.getComplexFieldArray(fieldName);
        if(arr.length>0 && pos>=0 && pos<arr.length){
            res = arr[pos];
        }
        return res;
    },
    
    doFormSubmit: function(formInputs,formAction,formMethod,formTarget){
        var formElem = document.getElementById(ncm.concat("tmp-form-submit-",this.id));
        if(!formElem){
            $jq("body").append(ncm.concat("<form id=\"tmp-form-submit-",this.id,"\" style=\"visibility:hidden;\"><\/form>"));
        }    
        var jqForm = $jq(ncm.concat("#tmp-form-submit-",this.id));
        jqForm.attr({
            action: formAction?formAction:"",
            method: formMethod?formMethod:"post",
            target: formTarget?formTarget:"_top"        
        });
        jqForm.html(formInputs);
        jqForm.submit();
        jqForm.remove();
    }
};


