﻿if (typeof (jQuery) == 'undefined')
    throw "Cossette.CMS library requires jQuery 1.4 +";

var Cossette = Cossette || {};
Cossette.CMS = {};

Cossette.CMS.v = Cossette.CMS.version = '4.0.3';
Cossette.CMS.Config = {
    datatype: 'XML', /* XML|JSON */
    serviceUrl: '',
    assetsUrl: '',
    cultureCode: ''
};

/* Enums
* --------------------------*/
Cossette.CMS.ImageSize = { SMALL: '2_', LARGE: '1_', SOURCE: '' };

/* Pager
* --------------------------*/
Cossette.CMS.Pager = function(options){
	this.opts = $.extend({}, Cossette.CMS.Pager.DefaultOptions, options);
	this.currentPage = (this.opts.startRowIndex / this.opts.maximumRows) + 1;
	this.totalPages = (this.opts.totalRows / this.opts.maximumRows);
	this._render();
};

Cossette.CMS.Pager.prototype._render = function(){
	var self = this;
	var opts = this.opts;
	var ul = $('<ul class="'+opts.pagerClass+'"></ul>')
	for(var i = 0; i < this.totalPages; i ++){
		var li = $('<li class="' + opts.itemClass + '"><a href="javascript:;">'+(i+1)+'</a></li>');
		(function(item, index){
			item.children('a').click(function(){
				opts.onClick(index * opts.maximumRows + 1, opts.maximumRows);
				self.update(index+1);
			});
		})(li, i);
		ul.append(li);
	}
	var container = $(opts.selector)
	container.append(ul);
	
	if(opts.showNextPrevious === true){
		$('<a href="javascript:;" class="prev">&laquo;</a>').click(function(){
			self.currentPage = self.currentPage > 1 ? self.currentPage - 1 : 1;
			opts.onClick((self.currentPage - 1) * opts.maximumRows + 1, opts.maximumRows);
			self.update(self.currentPage);
		}).prependTo(container);
		$('<a href="javascript:;" class="next">&raquo;</a>').click(function(){
			self.currentPage = self.currentPage < self.totalPages ? self.currentPage + 1 : self.totalPages;
			opts.onClick((self.currentPage - 1) * opts.maximumRows + 1, opts.maximumRows);
			self.update(self.currentPage);
		}).appendTo(container);
	}
	
	self.update(self.currentPage);
};

Cossette.CMS.Pager.prototype.update = function(pageNumber){
	var opts = this.opts;
	var container = $(opts.selector);
	this.currentPage = pageNumber;
	container.children('ul').children('li').removeClass('active').eq(this.currentPage - 1).addClass('active');
	if(opts.showNextPrevious === true){
		if(this.currentPage <= 1){
			container.children('.prev').hide();
			container.children('.next').show();
		} else if(this.currentPage >= this.totalPages){
			container.children('.prev').show();
			container.children('.next').hide();
		}
	}
};

Cossette.CMS.Pager.DefaultOptions = {
	selector: '',
	startRowIndex: 0,
	maximumRows:0,
	totalRows:0,
	pagerClass:'',
	itemClass:'',
	showNextPrevious: true,
	windowSize: 2,
	onClick: $.noop
};

/* Utils
* --------------------------*/
Cossette.CMS.Utils = {};

Cossette.CMS.Utils.isNullOrEmpty = function(value) {
	return value == null || value == '';
};

Cossette.CMS.Utils.normalizeParams = function(params, args) {
	if (typeof (args) != 'undefined')
		$.extend(params, args);
	if (typeof (params.nodeID) != 'undefined' && params.nodeID == '')
		throw 'Params nodeID not specified.';
	if (typeof (params.parentID) != 'undefined' && params.parentID == '')
		throw 'Params parentID not specified.';
	if (typeof (params.item) != 'undefined' && params.item == '')
		throw 'Params item not specified.';
	if (typeof (params.cultureCode) == 'undefined' || params.cultureCode == '')
		if (Cossette.CMS.Config.cultureCode != '')
		params.cultureCode = Cossette.CMS.Config.cultureCode;
	else
		throw 'Params cultureCode not specified and no default cultureCode in Cossette.CMS.Config.cultureCode.';
	if (typeof (params.modelCode) != 'undefined' && params.modelCode == '')
		throw 'Params modelCode not specified.';
	if (typeof (params.startRowIndex) != 'undefined' && params.startRowIndex == '')
		params.startRowIndex = 0;
	if (typeof (params.depth) != 'undefined' && params.depth == '')
		params.depth = 0;
	if (typeof (params.maximumRows) != 'undefined' && params.maximumRows == '')
		params.maximumRows = 0;
	if (typeof (params.orderBy) != 'undefined' && params.orderBy == '')
		params.orderBy = 'NodeOrder';
	return params;
};
Cossette.CMS.Utils.parseXMLPages = function(data) {
    var c = { 'ps': new Array(), 'totalCount': 0 };
    var ps = $(data);
    ps.find('p').each(function() {
        var p = new Cossette.CMS.CMPage(this);
        c.ps.push(p);
    });
    c.totalCount = parseInt(ps.find('ps').attr('t'), 10);
    return c;
};

/* CMPage
* --------------------------*/
Cossette.CMS.CMPage = function(data) {
    var p = this;
    var pageNode = $(data);
    /* properties */
    p.nodeID = pageNode.attr('id');
    p.parentID = pageNode.attr('pid');
    p.cultureCode = pageNode.attr('c');
    p.modelCode = pageNode.attr('m');
    p.pageName = pageNode.attr('n');
    p.pagePath = pageNode.attr('pp');
    p.updated = pageNode.attr('u');
    p.url = pageNode.attr('url');
    if (p.url == undefined) p.url = '';
    p.items = null;
    p.subpages = null;
    /* items */
    p._parseXMLItems(pageNode);
    /* subpages */
    p._parseXMLSubpages(pageNode);
};

Cossette.CMS.CMPage.prototype._parseXMLSubpages = function(pageNode) {
    var subpagesNode = pageNode.children('ps');
    if (subpagesNode.length) {
        this.subpages = new Array();
        var subpages = subpagesNode.children('p');
        for (var i = 0; i < subpages.length; i++)
            this.subpages.push(new Cossette.CMS.CMPage(subpages.eq(i)));
    }
};

Cossette.CMS.CMPage.prototype._parseXMLItems = function(pageNode) {
    var itemsNode = pageNode.children('is');
    if (itemsNode.length) {
        this.items = new Array();
        var items = itemsNode.children('i');
        for (var i = 0; i < items.length; i++)
            this.items[items.eq(i).attr('c')] = items.eq(i).text();
    }
};

Cossette.CMS.CMPage.prototype.dump = function() {
    var output = '';
    for (var k in this) {
        var isfunction = typeof (this[k]) == 'function';
        var isarray = typeof (this[k]) == 'object';
        if (isarray && this[k] != null) {
            output += '<em>' + k + '</em>' + ' = [<br />';
            for (var i in this[k])
                output += '<em>&nbsp;&nbsp;' + i + '</em>' + ' = ' + this[k][i] + '<br />';
            output += ']<br />';
        } else if (!isfunction || (k.charAt(0) != '_' && k != 'dump'))
            output += '<em>' + k + '</em>' + ' = ' + (isfunction ? 'function(){}' : this[k]) + '<br />';
    }
    return output;
};

Cossette.CMS.CMPage.prototype.isSubpagesLoaded = function() {
    return this.subpages != null;
};

Cossette.CMS.CMPage.prototype.isItemsLoaded = function() {
    return this.items != null;
};

Cossette.CMS.CMPage.prototype.loadSubpages = function(callback) {
    var p = this;
    var params = {
        'parentID': p.nodeID,
        'cultureCode': p.cultureCode,
        'orderBy': 'NodeOrder',
        'startRowIndex': 0,
        'maximumRows': 0
    };
    params = Cossette.CMS.Utils.normalizeParams(params);
    $.get(Cossette.CMS.Config.serviceUrl + '/Pages',
        params,
        function(data) {
            var c = Cossette.CMS.Utils.parseXMLPages(data);
            p.subpages = c.ps;
            callback(p, 0, 0, c.totalCount);
        }
    );
};

Cossette.CMS.CMPage.prototype.loadItems = function(callback) {
    var p = this;
    var params = { 'nodeID': p.nodeID, 'cultureCode': p.cultureCode };
    $.get(Cossette.CMS.Config.serviceUrl + '/Page', params,
            function(data) {
                var c = p._parseXMLItems($(data).find('p'));
                callback(p);
            }
        );
};

Cossette.CMS.CMPage.prototype.getItem = function(item, callback) {
    if (this.items == null && typeof (callback) == 'undefined') {
        throw 'Items not yet loaded, please provide a callback method or call loadItems()';
    } else if (this.items == null && typeof (callback) == 'function') {
        this.loadItems(callback);
    } else
        return this.items[item];
};

Cossette.CMS.CMPage.prototype.getAsset = function(item) {
    if (this.items == null && typeof (callback) == 'undefined')
        throw 'Items not yet loaded, please provide a callback method or call loadItems()';
    else if(Cossette.CMS.Config.assetsUrl == '')
        throw 'Assets\' url is not defined in Cossette.CMS.Config';
    else
        return Cossette.CMS.Config.assetsUrl + this.items[item];
};

Cossette.CMS.CMPage.prototype.getImage = function(item, imageSize) {
    
    if (this.items == null)
        throw 'Items not yet loaded, please call loadItems()';
    else if(Cossette.CMS.Config.assetsUrl == '')
        throw 'Assets\' url is not defined in Cossette.CMS.Config';
    else if(this.items[item] == '')
			return '';
    else
        return Cossette.CMS.Config.assetsUrl + (typeof(imageSize) != 'undefined' ? imageSize : '') + this.items[item];
};

/* CMServices
--------------------------*/
Cossette.CMS.CMServices = {};
Cossette.CMS.CMServices._getPage = function(method, params, callback) {
    $.get(Cossette.CMS.Config.serviceUrl + '/' + method,
        params,
        function(data) {
            var c = Cossette.CMS.Utils.parseXMLPages(data);
            callback((c.ps.length > 0 ? c.ps[0] : null));
        }
    );
};

Cossette.CMS.CMServices._getPages = function(method, params, callback) {
    $.get(Cossette.CMS.Config.serviceUrl + '/' + method,
        params,
        function(data) {
            var c = Cossette.CMS.Utils.parseXMLPages(data);
            callback(c.ps, params.startRowIndex, params.maximumRows, c.totalCount);
        }
    );
};

Cossette.CMS.CMServices._getBoolean = function(method, params, callback) {
    $.get(Cossette.CMS.Config.serviceUrl + '/' + method,
        params,
        function(data) {
            callback($(data).find('boolean').text() == 'true' ? true : false);
        }
    );
};

Cossette.CMS.CMServices.page = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true;
    args = Cossette.CMS.Utils.normalizeParams(args);
    this._getPage(loadItems ? 'Page' : 'PageLight', args, callback);
};

Cossette.CMS.CMServices.pageLight = function(args, callback) {
    Cossette.CMS.CMServices.page(args, callback, false);
};

Cossette.CMS.CMServices.pageExists = function(args, callback) {
    args = Cossette.CMS.Utils.normalizeParams(args);
    this._getBoolean('PageExists', args, callback);
};

Cossette.CMS.CMServices.pageByModel = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true;
    var params = {
        'modelCode': '',
        'query': '',
        'orderBy': '',
        'cultureCode': '',
        'startRowIndex': 0,
        'maximumRows': 0 };
    params = Cossette.CMS.Utils.normalizeParams(params, args);
    this._getPage(loadItems ? 'PageByModel' : 'PageLightByModel', params, callback);
};

Cossette.CMS.CMServices.pageLightByModel = function(args, callback) {
    Cossette.CMS.CMServices.pageByModel(args, callback, false);
};

Cossette.CMS.CMServices.pageLink = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true;
    var params = { 'nodeID':'', 'cultureCode':'', 'item':'' };
    params = Cossette.CMS.Utils.normalizeParams(params, args);
    this._getPage(loadItems ? 'PageLink' : 'PageLinkLight', params, callback);
};

Cossette.CMS.CMServices.pageLinkLight = function(args, callback) {
    Cossette.CMS.CMServices.pageLink(args, callback, false);
};

Cossette.CMS.CMServices.otherCulturePages = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true;
    args = Cossette.CMS.Utils.normalizeParams(args);
    this._getPages(loadItems ? 'OtherCulturePages' : 'OtherCulturePagesLight', args, callback);
};

Cossette.CMS.CMServices.otherCulturePagesLight = function(args, callback) {
    Cossette.CMS.CMServices.otherCulturePages(args, callback, false);
};

Cossette.CMS.CMServices.pageTrail = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true;
    args = Cossette.CMS.Utils.normalizeParams(args);
    this._getPages(loadItems ? 'PageTrail' : 'PageTrailLight', args, callback);
};

Cossette.CMS.CMServices.pageTrailLight = function(args, callback) {
    Cossette.CMS.CMServices.pageTrail(args, callback, false);
};

Cossette.CMS.CMServices.pageTrailWithoutEmptyNodes = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true;
    args = Cossette.CMS.Utils.normalizeParams(args);
    this._getPages(loadItems ? 'PageTrailWithoutEmptyNodes' : 'PageTrailLightWithoutEmptyNodes', args, callback);
};

Cossette.CMS.CMServices.pageTrailLightWithoutEmptyNodes = function(args, callback) {
    Cossette.CMS.CMServices.pageTrailWithoutEmptyNodes(args, callback, false);
};

Cossette.CMS.CMServices.pageTree = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true; 
    var params = { 'nodeID': '', 'cultureCode': '', 'depth': 0 };
    params = Cossette.CMS.Utils.normalizeParams(params, args);
    this._getPage(loadItems ? 'PageTree' : 'PageTreeLight', params, callback);
};

Cossette.CMS.CMServices.pageTreeLight = function(args, callback) {
    Cossette.CMS.CMServices.pageTree(args, callback, false);
};

Cossette.CMS.CMServices.pageWithSubpages = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true; 
    args = Cossette.CMS.Utils.normalizeParams(args);
    this._getPage(loadItems ? 'PageWithSubpages' : 'PageWithSubpagesLight', args, callback);
};

Cossette.CMS.CMServices.pageWithSubpagesLight = function(args, callback) {
    Cossette.CMS.CMServices.pageWithSubpages(args, callback, false);
};

Cossette.CMS.CMServices.pages = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true;
    var params = {
        'parentID': '',
        'cultureCode': '',
        'orderBy': '',
        'startRowIndex': 0,
        'maximumRows': 0
    };
    params = Cossette.CMS.Utils.normalizeParams(params, args);
    this._getPages(loadItems ? 'Pages' : 'PagesLight', params, callback);
};

Cossette.CMS.CMServices.pagesLight = function(args, callback) {
    Cossette.CMS.CMServices.pages(args, callback, false);
};

Cossette.CMS.CMServices.pagesByModel = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true;
    var params = {
        'cultureCode': '',
        'modelCode': '',
        'orderBy': '',
        'query': '',
        'startRowIndex': 0,
        'maximumRows': 0
    };
    params = Cossette.CMS.Utils.normalizeParams(params, args);
    this._getPages(loadItems ? 'PagesByModel' : 'PagesLightByModel', params, callback);
};

Cossette.CMS.CMServices.pagesLightByModel = function(args, callback) {
    Cossette.CMS.CMServices.pagesByModel(args, callback, false);
};

Cossette.CMS.CMServices.searchPages = function(args, callback, loadItems) {
    if (typeof (loadItems) == 'undefined')
        loadItems = true;
    var params = {
        'query': '',
        'orderBy': '',
        'cultureCode': '',
        'startRowIndex': 0,
        'maximumRows': 0
    };
    params = Cossette.CMS.Utils.normalizeParams(params, args);
    this._getPages(loadItems ? 'SearchPages' : 'SearchPagesLight', params, callback);
};

Cossette.CMS.CMServices.searchPagesLight = function(args, callback) {
    Cossette.CMS.CMServices.searchPages(args, callback, false);
};

Cossette.CMS.CMServices.subpagesByModel = function(args, callback) {
    var params = {
        'modelCode':'',
        'parentID': '',
        'cultureCode': '',
        'orderBy': '',
        'startRowIndex': 0,
        'maximumRows': 0
    };
    params = Cossette.CMS.Utils.normalizeParams(params, args);
    this._getPages('SubpagesByModel', params, callback);
};
