/* ------------------------------------------------------------------- */

/*
if (navigator.vendor.indexOf('Google') != -1) {
  $.browser.chrome = true;
  $.browser.mozilla = $.browser.msie = $.browser.opera = $.browser.safari = false;
} else {
  $.browser.chrome = false;
}
*/
$.browser.chrome = typeof navigator.vendor != 'undefined' && navigator.vendor.indexOf('Google') != -1;
$.browser.ie6 = typeof navigator.userAgent != 'undefined' && navigator.userAgent.indexOf('MSIE 6.') != -1;
$.browser.ie5 = typeof navigator.userAgent != 'undefined' && navigator.userAgent.indexOf('MSIE 5.') != -1;
$.browser.iPad = typeof navigator.userAgent != 'undefined' && navigator.userAgent.indexOf('iPad') != -1;
$.browser.iPhone = typeof navigator.userAgent != 'undefined' && navigator.userAgent.indexOf('iPhone') != -1;
$.browser.iPod = typeof navigator.userAgent != 'undefined' && navigator.userAgent.indexOf('iPod') != -1;

/*if (typeof skatic == 'undefined') {
  skatic = {};
}
skatic.browser = $.browser;
$.browser = function(){
  this.chrome = skatic.browser.chrome;
  this.mozilla = skatic.browser.mozilla;
  this.msie = skatic.browser.msie;
  this.opera = skatic.browser.opera;
  this.safari = skatic.browser.safari;
  this.version = skatic.browser.version;
};*/

/* ------------------------------------------------------------------- */

var skatic = new Object();

skatic.tmp = {};
skatic.onContentShow = {'once':[],'persist':[]};
skatic.beforeLoadPage = [];
skatic.siteStorage = {};
skatic.appliedAjaxMethods = {};

/* ------------------------------------------------------------------- */

if (typeof console == 'undefined') {
	if (document.location.host == 'skatic.localhost') {
	    console = {'log':function(obj){alert(obj);}};
	} else {
	    console = {'log':function(){}};
	}
} else if (typeof console.log == 'undefined') {
	if (document.location.host == 'skatic.localhost') {
	    console.log = function(obj){alert(obj);};
	} else {
	    console.log = function(){};
	}
}

/* ------------------------------------------------------------------- */

/*skatic.swfu = {};
skatic.swfu.instances = [];

skatic.swfu.destroyInstances = function() {
	//console.log('called skatic.swfu.destroyInstances instancesCount:'+skatic.swfu.instances.length);
	skatic.swfu.instances.foreach(function(key, value){
	if (typeof value != 'undefined') {
		value.destroy();
	}
	});
	skatic.swfu.instances = [];
}*/

skatic.uploadify = {
	'loaded': [],
	'checkTimeouts': {},
	'onInit': function() {
        var self = this;
        setTimeout(function(){

            $('#loading_'+self.id).hide();

            skatic.uploadify.loaded.push(self.id); //add to loaded

            skatic.beforeLoadPage.push(function(newLocation){ //remove from loaded
                delete skatic.uploadify.loaded[skatic.uploadify.loaded.indexOf(self.id)];
            });

        },	1500);
        return true;
	},
	'checkLoaded': function(selector) {
        var id = $(selector).attr('id');

        $(selector).hide();
        $('#loading_'+id).show();

        skatic.uploadify.checkTimeouts[id] = setTimeout(function(){
            if (skatic.uploadify.loaded.indexOf(id) === -1) {
            $(selector).show();
            skatic.flash([_('Please upgrade your flash to use flash uploader.'), 'error']);
            }
        }, 7000);

        skatic.beforeLoadPage.push(function(newLocation){ //clear check timeout
            if (typeof skatic.uploadify.checkTimeouts[id] != 'undefined') {
            clearTimeout(skatic.uploadify.checkTimeouts[id]);
            }
        });
	}
};

/* --------------------------------------------------------------------- */

function getTopDomain() {
	var httpHost = document.location.hostname;
	httpHost = httpHost.split('.');

	var level = httpHost.length;
	var isUserDomain;

	if (httpHost[level - 1] == 'com' || httpHost[level - 1] == 'net') {
        if (httpHost[level - 2] == 'shakuro') {
            if (level == 3) {
            isUserDomain = false;
            } else {
            isUserDomain = true;
            }
        } else {
            if (level == 2) {
            isUserDomain = false;
            } else {
            isUserDomain = true;
            }
        }
	} else if (httpHost[level - 1] == 'localhost') {
        if (level == 2) {
            isUserDomain = false;
        } else {
            isUserDomain = true;
        }
	}

	if (isUserDomain) {
	    httpHost = httpHost.slice(1);
	}
	return httpHost.join('.');
}
var siteTopDomain = getTopDomain();

/* --------------------------------------------------------------------- */

function createCookie(name,value,days) {
	if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
	} else {
	    var expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/; domain=."+siteTopDomain;
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
  createCookie(name,"",-1);
}


/*function changeViewType(checkbox) {
	var checked = $(checkbox).attr('checked') ? true : false;
	if (checked) {
	var view = '';
	} else {
	var view = 'view:simple';
	}

  var currentLocation = location.href;

  reg = new RegExp('http://([^/]*)/');
  currentLocation = currentLocation.replace(reg, '/');
  reg = new RegExp('(view:[^/]*)');
  currentLocation = currentLocation.replace(reg, '');

	if (currentLocation[currentLocation.length - 1] != '/') {
	currentLocation += '/';
	}

  location.href = currentLocation+view;
}*/




/*-------------------------------------------------[ tree ]---------------------------------------*/

var moveTreeElementData = {'from':{'pk':0,'name':''}, 'to':{'pk':0,'name':''}};
function moveTreeElement(pk, name, moveUrl) {
	//last slash
	if (moveUrl.charAt(moveUrl.length - 1) != '/') {
	    moveUrl += '/';
	}

	if (moveTreeElementData.from.name == '') {
        if (pk == 0) {
            return;
        }
        moveTreeElementData.from = {'pk':pk, 'name':name};
        alert("You have selected '"+name+"' element to move.\n Now select destination element.");
	} else if (moveTreeElementData.to.name == '') {
        moveTreeElementData.to = {'pk':pk, 'name':name};
        var res = confirm("Move element '"+moveTreeElementData.from.name+"' to '"+moveTreeElementData.to.name+"'?");
        if (res) {
            moveUrl += moveTreeElementData.from.pk+'/'+moveTreeElementData.to.pk+'/';
            $.ajax({
                'url':moveUrl,
                'type':'GET',
                'dataType':'json',
                'success':function(response){
                    if (response.result == 'success') {
                        skatic.refreshPage(true);
                        //document.location.reload(false);
                    } else {
                        alert(response.message);
                    }
                },
                'cache':false
            });
        }
        moveTreeElementData = {'from':{'pk':0,'name':''}, 'to':{'pk':0,'name':''}}; //empty
	}
}

/* ------------------------------------------------------------------ */

skatic.invalidateFields = function(fields){
  $('.error-message').remove();

  var contentSelector = '#wrapper';

	var invalidate = function(selector, validationError){
	    $(selector).after('<div class="error-message">'+validationError+'</div>');
	}
	for (field in fields) {
        //if (field.indexOf('.') != -1) {
            var exploded = field.split('.');
            var name = 'data['+exploded[0]+']['+exploded[1]+']';
            if (exploded.length == 3) {
                name += '['+exploded[2]+']';
            }

            var validInputTypes = ["submit", "reset", "radio", "password", "image", "file", "checkbox", "button", "text", "hidden"];
            var inputSelector = '';
            validInputTypes.foreach(function(key, value){
                inputSelector += contentSelector+' input[name="'+name+'"][type="'+value+'"],';
            });

            var sel = inputSelector+' '+contentSelector+' textarea[name="'+name+'"], '+contentSelector+' select[name="'+name+'"], '+contentSelector+' img[title="'+name+'"]';
            invalidate(sel, fields[field]);
        //}
	}
};

/* ------------------------------------------------------------------ */

function sortList(link, tagName) {
	var id = link.id.split('_')[1];

	if (typeof tagName == 'undefined') {
	    var tagName = $(link).parent().get(0).tagName.toLowerCase(); //can be "tr" or "li" or anything else
	}

	$.ajax({
        'type':'GET',
        'url':skatic.parseLinkUrl(link.href)+'?call=ajax',
        'cache':false,
        'dataType':'json',
        'success':function(response){
            if (typeof response.result != 'undefined' && response.result == 'success') {
                var firstId = tagName+'_'+id;
                var secondId = tagName+'_'+response.replacedWith;
                var direction = response.direction;

                if ($('#'+secondId).length == 0) {
                    if (direction == 'up') {
                        var prevLink = $('#content').find('a[rel="previous"]');
                        if (prevLink.length == 0) {
                            return false;
                        }
                        if (confirm(_('Switch to previous page?'))) {
                            skatic.redirect(skatic.parseLinkUrl(prevLink.attr('href')));
                        }
                    } else if (direction == 'down') {
                        var nextLink = $('#content').find('a[rel="next"]');
                        if (nextLink.length == 0) {
                            return false;
                        }
                        if (confirm(_('Switch to next page?'))) {
                            skatic.redirect(skatic.parseLinkUrl(nextLink.attr('href')));
                        }
                    }
                    return false;
                }

                var currentHtml = $('#'+firstId).html();
                var replacedHtml = $('#'+secondId).html();

                $('#'+firstId).replaceWith('<'+tagName+' id="'+tagName+'_current"></'+tagName+'>');
                $('#'+secondId).replaceWith('<'+tagName+' id="'+tagName+'_replace"></'+tagName+'>');

                $('#'+tagName+'_current').replaceWith('<'+tagName+' id="'+secondId+'">'+replacedHtml+'</'+tagName+'>');
                $('#'+tagName+'_replace').replaceWith('<'+tagName+' id="'+firstId+'">'+currentHtml+'</'+tagName+'>');

            } else {
                skatic.parseJsonResponse(response);
            }
        }
	});

	return false;
}



/* --------------------------------- expander -----------------------------------*/

skatic.expander = {
  'defaultHeight': {}
};

skatic.expander.expand = function() {
	var parent = $(this).prev();
	var elem = parent.children(':first');

	parent.height('');

	$(this).attr('title', 'Collapse').removeClass('expand').addClass('collapse').click(skatic.expander.collapse);
	return false;
};


skatic.expander.collapse = function() {
	var parent = $(this).prev();
	var elem = parent.children(':first');

	var uniqId = $(this).data('uniqId');

	parent.height(skatic.expander.defaultHeight[uniqId]);

	$(this).attr('title', 'Expand').removeClass('collapse').addClass('expand').click(skatic.expander.expand);
};

skatic.showExpander = function(elemSelector) {
	var elem = $(elemSelector);
	var parent = elem.parent();

	if (elem.height() > 0 && parent.height() > 0) {
        if (elem.height() > parent.height()) {

            var uniqId = Math.random();

            parent.next().show().data('uniqId', uniqId).click(skatic.expander.expand);

            skatic.expander.defaultHeight[uniqId] = parent.height();
        }
	} else {
	    setTimeout(function(){ skatic.showExpander(elemSelector); }, 200);
	}
};

/* --------------------------------- current user ------------------------------*/

skatic.user = {
	'id':null,
	'avatarUrl':{
        'thumb':null,
        'large':null
	}
};

skatic.user.isLoggedIn = function() {
	try {
	    return $('#profilemenu').is(':visible');
	} catch (e) {
	    return false;
	}
};

skatic.user.liveAvatarUrl = function() {
	if (skatic.user.id === null || skatic.user.avatarUrl.thumb === null || skatic.user.avatarUrl.large === null || skatic.user.avatarUrl.new200 === null) {
	    return false;
	}

	$('img[longdesc="avatar_'+skatic.user.id+'"]').each(function(){
        if (this.src.indexOf('thumb') != -1) {
            this.src = skatic.user.avatarUrl.thumb+'?_='+Math.random();
        } else {
            this.src = skatic.user.avatarUrl.large+'?_='+Math.random();
        }
	});
};

/*------------------------[ playlists ]--------------------------------*/

skatic.playlists = {};

skatic.playlists.closeOpenPlaylist = function(link) {
	var playlistId = link.id.split('_')[1];

	if ($('#playlist_dd_'+playlistId).html().replace('&nbsp;', '').trim() == '') {
	    skatic.appliedAjaxMethods.getPlaylistRecords(link);
	} else {
	    skatic.playlists.doOpenClosePlaylist(link);
	}

	return false;
};

skatic.playlists.doOpenClosePlaylist = function(link) {
	var closed = $(link).find('img').attr('title').toLowerCase().indexOf('close') == -1;
	if (closed) {
        $(link).parents('dt').next('dd').slideDown();
        $(link).find('img').attr('title', 'Close').attr('src', '/img/close.gif');
	} else {
        $(link).parents('dt').next('dd').slideUp();
        $(link).find('img').attr('title', 'Open').attr('src', '/img/open.gif');
	}
};

/*----------------------------------------------------------*/

skatic.flash = function(flash, className) {
	var div = $('div.flashmessage');
	if (div.length > 0) {
	    div.remove();
	}

	if (typeof className != 'undefined') {
	    flash = [flash, className];
	}

  var showTime = flash[0].length / 15; //seconds = length / 15
  showTime = (showTime < 5) ? 5000 : showTime * 1000; //ms, min 5000

  var div = $('<div class="flashmessage '+flash[1]+'" style="right: -265px;"><h4>'+flash[0]+'</h4></div>');

	$('#global_loading').after(div);

	div.animate({'right':'0px'});
	setTimeout(function(){
	    div.animate({'right':'-265px'});
	}, showTime);
	//alert(flash[0]+'	 ['+flash[1]+']');
};

/* ------------------------------------------------------------------------------------ */

skatic.layoutReady = function(){
	try {
        $('#layoutSearchForm').ajaxForm({'success':skatic.ajaxResponse});
        $('#loginForm').ajaxForm({'success':skatic.ajaxResponse});
	} catch (e) {
	    //pass
	}

	$('#layoutSearchInput').bind('focus', function(){
        if ($(this).val() == _('Search')) {
            $(this).val('');
        }
	}).bind('blur', function(){
        if ($(this).val() == '') {
            $(this).val(_('Search'));
        }
	});
};

$(function(){
	if (skatic.user.isLoggedIn()) { //registered user
	    setTimeout(skatic.appliedAjaxMethods.getUnreadPmCount, 120000); //2 mins
	}

	skatic.cookieSettings = readCookie('settings');
	if (!skatic.cookieSettings) {
	    skatic.cookieSettings = {};
	} else {
	    skatic.cookieSettings = JSON.parse(skatic.cookieSettings);
	}

	$(window).resize(function(){
		if (skatic.bgImage.scaleTimeout != null) {
			return false;
		}

		skatic.bgImage.scaleTimeout = setTimeout(function(){
			skatic.bgImage.scale();
			skatic.bgImage.scaleTimeout = null;
		}, 50);
	});

	if ($.browser.ie6 || $.browser.ie5) {
        if (!readCookie('ie6noticed')) {
	        createCookie('ie6noticed', true, 365);
            //loadPage('/systems/ie6notice/');
            document.location.href = '/systems/ie6notice/';
        }
	}

	skatic.layoutReady();
});

/*
function aaa(c,p){
	if(!p){
	p={}
	}
	var q=(p.bg_img?p.bg_img:t61.background.get_bg_img());
	if(!q){
	return;
	}
	var preloader=new Image();
	var d=q.getAttribute("src");
	if(!d){
	return
	}
	preloader.src=d;
	var imgSizes={
	width:l.width,
	height:l.height
	};
	var winSize=t61.util.get_viewport();
	var widthCoeff=winSize.width/imgSizes.width;
	var heightCoeff=winSize.height/imgSizes.height;
	if((widthCoeff > 1)||(heightCoeff > 1)||((widthCoeff < 1)&&(heightCoeff < 1))) {
	diff = (widthCoeff > heightCoeff) ? widthCoeff : heightCoeff
	} else {
	diff=1;
	}
	newWidth=preloader.width * diff;
	newHeight=preloader.height * diff;
	if(!newWidth||!newHeight){
	return;
	}
	q.style.width=newWidth+"px";
	q.style.height=newHeight+"px";

	q.style.top=parseInt(0.25*(winSize.height-newHeight))+"px";
	q.style.left=parseInt(0.5*(winSize.width-newWidth))+"px";

	q.setOpacity(0.99);
	extra_bgs=$("page_content").getElementsByClassName("fill_background");

	for(var j=0;j<extra_bgs.length;j++){
	var h=$(extra_bgs[j]);
	h.style.height=winSize.height+"px"
	}
	if(t61.popup.filled){
	t61.popup.fill()
	}
	return {
	width:newWidth,
	height:newHeight
	}
}
*/

skatic.bgImage = {
  'scaleTimeout': null
};

skatic.bgImage.change = function(newBgImage) {
  var defImgArray = ['turntable']; //, 'organ', 'piano'
  var defImg = '/img/profileimg/turntable.jpg'; //defImgArray[rand(0, 2)]

	if (typeof newBgImage == 'undefined' || newBgImage == null || newBgImage == defImg) {
	    newBgImage = defImg;
	    var isDefault = true;
	} else {
	    var isDefault = false;
	}

	if ($('.profile-image').attr('src') != newBgImage) {
        var preloader = new Image();
        preloader.onload = function() {
            $('.profile-image').attr('src', newBgImage);
            setTimeout(function(){skatic.bgImage.scale();}, 50);
        }
        preloader.src = newBgImage;
	}

	if (!isDefault) {
        skatic.beforeLoadPage.push(function(newLocation){

            if (!skatic.isProfilePage(newLocation)) {
                skatic.bgImage.change(); //to default
            }
        });
	}
};
skatic.bgImage.scale = function() {
	if ($('.profile-image').length == 0) {
	    return false;
	}

	var img = new Image();
	img.onload = function() {
        /*var newWidth = $(window).width();
        var coeffOriginal = img.width / img.height;
        var coeffNewWidth = img.width / newWidth;
        var newHeight = newHeight * coeffOriginal * coeffNewWidth;*/

        var widthCoeff = $(window).width() / img.width;
        var heightCoeff = $(window).height() / img.height;
        if((widthCoeff > 1) || (heightCoeff > 1) || ((widthCoeff < 1) && (heightCoeff < 1))) {
            if (widthCoeff > heightCoeff) {
                var biggerCoeff = widthCoeff;
            } else {
                var biggerCoeff = heightCoeff;
            }
        } else {
            var biggerCoeff = 1;
        }
        var newWidth = img.width * biggerCoeff;
        var newHeight = img.height * biggerCoeff;

        var newTop = parseInt(0.3 * ($(window).height() - newHeight)) + "px"; //0.25
        var newLeft = parseInt(0.5 * ($(window).width() - newWidth)) + "px";

        $('.profile-image').css({
            'width':newWidth,
            'height':newHeight,
            'left':newLeft,
            'top':newTop//(($(window).height() - newHeight) / 2) + 'px'
        });
	};
	img.src = $('.profile-image').attr('src');
};

/* ------------------------------------------------------------------------------------ */

skatic.url = {};
skatic.url.removeParams = function(url) {
	var reg = new RegExp('https?://([^/]*)/');
	url = url.replace(reg, '/');

	reg = new RegExp('([^/]+:[^/]+)');
	url = url.replace(reg, '');

	url = skatic.url.removeGetParams(url);

	url = url.replace(/\/\//g, '/');

	return url;
};
skatic.url.removeGetParams = function (url) {
	var reg = new RegExp('\\?.*');
	url = url.replace(reg, '');
	return url;
};
skatic.url.current = function(removeParams) {
	var currentLocation = skatic.ajax.current;

	if (typeof removeParams == 'undefined') {
	    removeParams = true;
	}

	if (removeParams) {
	    return skatic.url.removeParams(currentLocation);
	} else {
	    return currentLocation;
	}
};
skatic.url.getNamedParam = function(url, name, defaultValue) {
	var reg = new RegExp(name+':([^/\?]+)');
	var match = url.match(reg);
	if (match === null || typeof match[1] == 'undefined') {
        if (typeof defaultValue != 'undefined') {
            return defaultValue;
        } else {
            return null;
        }
	} else {
	    return match[1];
	}
};
skatic.url.getGetParam = function(url, name, defaultValue) {
	var reg = new RegExp('(\\?|&)'+name+'=([^&]+)');
	var match = url.match(reg);
	if (match === null || typeof match[2] == 'undefined') {
        if (typeof defaultValue != 'undefined') {
            return defaultValue;
        } else {
            return null;
        }
	} else {
	    return match[2];
	}
};

skatic.url.changeNamedParam = function(url, name, value) {
	var currentValue = skatic.url.getNamedParam(url, name);
	if (currentValue !== null) {
	    return url.replace(name+':'+currentValue, name+':'+value);
	} else {
        if (url.indexOf('?') == -1) {
            if (url.charAt(url.length - 1) != '/') {
                url += '/'; //last must be slash
            }
            return url+name+':'+value+'/';
        } else {
            var start = url.substr(0, url.indexOf('?'));
            var end = url.substr(url.indexOf('?'));

            if (start.charAt(start.length - 1) != '/') {
                start += '/'; //last must be slash
            }
            return start+name+':'+value+'/'+end;
        }
	}
};
/**
 * use: skatic.url.changeGetParam(url, name, value) or skatic.url.changeGetParam(url, {name1:value1, name2:value2,...})
 */
skatic.url.changeGetParam = function(url, name, value) {
	if (typeof name == 'object') {
        for (key in name) {
            url = skatic.url.changeGetParam(url, key, name[key]);
        }
        return url;
	}

	var query = $.url.setUrl(url).attr('query');

	if (query != null) {
        var reg = new RegExp(name+'=[^&]+');
        var current = query.match(reg);
        if (current) {
            if (value == null || value == '') {
                var newQuery = query.replace(current, '');
            } else {
                var newQuery = query.replace(current, name+'='+value);
            }
            if (newQuery[0] == '&') {
                newQuery = newQuery.substr(1);
            }
        } else {
            newQuery = query+'&'+name+'='+value;
        }
        url = url.replace(query, newQuery);
	} else {
	    url = url+'?'+name+'='+value;
	}

	if (url[url.length - 1] == '?' || url[url.length - 1] == '&') {
	    url = url.substr(0, url.length - 1);
	}

	return url;
};

skatic.url.split = function(url) {
	url = skatic.url.removeParams(url);

	if (url.charAt(0) == '/') {
	    url = url.substr(1);
	}

	var pos = url.indexOf('/');
	if (pos != -1) {
	    url = url.substr(0, pos);
	}

	return url.split('/');
};

skatic.url.getUrlFromHref = function(href) {
	href = href.split('#');
	if (href.length == 1) {
	    return href[0];
	} else if (href.length == 2) {
        if (href[1] == '') {
            return href[0];
        } else if (href[0] == '') {
            return href[1];
        }
	}
};

/* -----------------------------[ XPath ]------------------------------------------------------- */

function getXPath(node, path) {
	path = path || [];
	if(node.parentNode) {
	    path = getXPath(node.parentNode, path);
	}

	if(node.previousSibling) {
        var count = 1;
        var sibling = node.previousSibling
        do {
            if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {count++;}
            sibling = sibling.previousSibling;
        } while(sibling);
        if(count == 1) {count = null;}
	} else if(node.nextSibling) {
        var sibling = node.nextSibling;
        do {
            if (sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {
                var count = 1;
                sibling = null;
            } else {
                var count = null;
                sibling = sibling.previousSibling;
            }
        } while(sibling);
	}

	if(node.nodeType == 1) {
	    path.push(node.nodeName.toLowerCase() + (node.id ? "[@id='"+node.id+"']" : count > 0 ? "["+count+"]" : ''));
	}
	return path;
}

/*function getXPath(elt) {
	var path = "";
	for (; elt && elt.nodeType == 1; elt = elt.parentNode) {
	idx = getElementIdx(elt);
	xname = elt.tagName;
	if (idx > 1) xname += "[" + idx + "]";
	path = "/" + xname + path;
	}
	path = path.split('/').clean("");
	return path;
}
function getElementIdx(elt) {
	var count = 1;
	for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling) {
		if(sib.nodeType == 1 && sib.tagName == elt.tagName)	count++
	}
	return count;
}*/

/*function getXPath(element) {
	if (element.id !== '') {
		return 'id("'+element.id+'")';
	}
	if (element === document.body) {
		return element.tagName;
	}

	var ix = 0;

	try {
		var siblings = element.parentNode.childNodes;
	} catch (e) {
		return null;
	}
//	console.log('--------------------');
	for (var i = 0; i < siblings.length; i++) {
		var sibling = siblings[i];
//		console.log(sibling === element, '	 |	 ', ix, '	 |	 ', sibling.nodeType, '	 |	 ', sibling.tagName);
		if (sibling === element) {
			return getXPath(element.parentNode)+'/'+element.tagName+'['+(ix + 1)+']';
		}
		if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {
			ix++;
		}
	}
}*/

$.fn.XPathSelector = function() {
	var self = this[0];
	var XPath = getXPath(self);

	return $.selectorByXPath(XPath);
};

$.selectorByXPath = function(XPath) {
	if (typeof XPath == 'string') {
		XPath = XPath.split('/').clean('');
	}
	XPath = XPath.join(' > ').replace(new RegExp('\\[@', 'g'), '[');
	var reg = new RegExp('\\[([0-9]+)\\]');
	while (reg.test(XPath)) {
		var num = parseInt( XPath.match(reg)[1] );
		XPath = XPath.replace(new RegExp('\\['+num+'\\]'), ':eq('+(num - 1)+')');
	}
	reg = new RegExp('id\\("([^"]+)"\\)');
	while (reg.test(XPath)) {
		var match = XPath.match(reg);
		XPath = XPath.replace(match[0], '#'+match[1]);
	}

	return XPath;
};

$.findByXPath = function(XPath) {
	var XPathSelector = $.selectorByXPath(XPath);
	return $.find(XPathSelector);
};

/* ------------------------------------------------------------------------------------ */


skatic.autocomplete = {};
skatic.autocomplete.multipleGetValue = function(element, itemFromAjax) {
  //console.log('--------------- get -----------------', element);

  element = $(element);


  if (typeof itemFromAjax != 'undefined' && typeof itemFromAjax.value != 'undefined') {
    var previous = $.data(element[0], 'previous');
    if (!previous) {
      previous = [];
    }
    var current = $(element).val().split(',');
    current.map(function(elem, key){
      current[key] = elem.trim();
    });

    for (var i = 0; i < current.length - 1; i++) { //do not include last incomplete word
      previous.push(current[i]);
    }

    previous = previous.unique();

		previous = previous.clean('');
		//console.error('stored', previous);
		$.data(element[0], 'previous', previous);


    return itemFromAjax.value;
  }


  var val = $(element).val().trim();

  //			console.log('val', val);

	if (val.indexOf(',') == -1) {
	    return val;
	}

	var words = val.split(',');
	words.map(function(elem, key){
	    words[key] = elem.trim();
	});

  //			console.info(words);

  return words[words.length - 1];
};
skatic.autocomplete.multipleSetValue = function(element, value, fromMethod) {
  //			console.log('--------------- set -----------------', element, value, fromMethod);

	if (fromMethod == 'blur') {
	    value = '';
	}

  var val = htmlspecialchars_decode(html_entity_decode(html_entity_decode( value ))).trim();

  //			console.log('val', val);



	if (val.indexOf(',') != -1) {
        var words = val.split(',');
        words.map(function(elem, key){
            words[key] = elem.trim();
        });
        val = words[words.length - 1];
	}

	var prevData = $.data(element[0], 'previous');
	if (typeof prevData != 'undefined' && prevData !== null) {
        var previous = [];
        for (var i = 0; i < prevData.length; i++) {
            previous.push(prevData[i]);
        }
        previous.push(val);
        previous = previous.unique();
	} else {
	    //				console.log('1111111');
	    var previous = [val];
	}

  //			console.warn('previous', previous);

	if (fromMethod == 'selected') {
        //				console.error('stored', previous);
        previous = previous.clean('');
        $.data(element[0], 'previous', previous);
	}

  val = previous.join(', ');
  val += ',';

  //			console.info('set', '__', value, '__', fromMethod, '__', val);

	element.val(val);
	element.each(function(){
        setSelectionRange(this, val.length, val.length);
        this.focus();
	});
	return true;
};

/* ------------------------------------------------- */

skatic.markLinksBasedOnCurrentUrl = function(urlNamedParam, def) {
	var addOrRemoveClass = function(link, add, className) {
		var elem = $(link);

		if (elem.parent().is('span')) {
			elem = elem.parent();
		}

		if (add) {
			elem.addClass(className);
		} else {
			elem.removeClass(className);
		}
	};

	var currentNamedParam = skatic.url.getNamedParam(skatic.url.current(false), urlNamedParam);

	$('a[rel^="'+urlNamedParam+':"]').each(function(){

		var relVal = $(this).attr('rel').split(urlNamedParam+':')[1].trim();

		if (currentNamedParam == null) {
			if (typeof def != 'undefined' && relVal == def) {
				addOrRemoveClass(this, true, 'on');
			} else {
				addOrRemoveClass(this, false, 'on');
			}
		} else if (currentNamedParam == relVal) {
			addOrRemoveClass(this, true, 'on');
		} else {
			addOrRemoveClass(this, false, 'on');
		}

	});
};

/* ------------------------------------------------------------------------------------ */

function _(s) {
	var lang = readCookie('language');
	if (!lang) {
		lang = 'eng';
	}

    if (typeof (skatic.i18n) != 'undefined' && typeof (skatic.i18n[lang]) != 'undefined' && typeof skatic.i18n[lang][s] != 'undefined') {
        return skatic.i18n[lang][s];
    }
    return s;
}

function _n(s, p, n) {
	var lang = readCookie('language');
	if (!lang) {
		lang = 'eng';
	}

    if (n != 1) {
        if (typeof (skatic.i18n) != 'undefined' && typeof (skatic.i18n[lang]) != 'undefined' && typeof skatic.i18n[lang][s][1] != 'undefined') {
            return skatic.i18n[lang][s][1];
        } else {
            return p;
        }
    } else {
        if (typeof (skatic.i18n) != 'undefined' && typeof (skatic.i18n[lang]) != 'undefined' && typeof skatic.i18n[lang][s][0] != 'undefined') {
            return skatic.i18n[lang][s][0];
        } else {
            return s;
        }
    }
}
