$.browser.chrome = typeof navigator.vendor != 'undefined' && navigator.vendor.indexOf('Google') != -1;

if (typeof console == 'undefined') {
	if (document.location.host == 'cghub.localhost') {
		console = {'log':function(obj){alert(obj);}};
	} else {
		console = {'log':function(){}};
	}
} else if (typeof console.log == 'undefined') {
	if (document.location.host == 'cghub.localhost') {
		console.log = function(obj){alert(obj);};
	} else {
		console.log = function(){};
	}
}

function getTopDomain() {
	var httpHost = document.location.hostname;
	httpHost = httpHost.split('.');
	
	var level = httpHost.length;
	var isUserDomain;
	
	if (httpHost[level - 1] == 'com') {
		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();








jQuery.fn.getSelectedText = function() {
	var a;
	this.each(function() {		
		if (this.tagName == 'SELECT') {
			var selectElement = this;
			a = selectElement.options[selectElement.options.selectedIndex].text;
		}			
	});
	return a;	
}

$.fn.ajaxSubmit = function(e) {
	/* Change a form's submission type to ajax */
	this.submit(function(){
		var params = {};
		$(this)
		.find("input[@checked], input[@type='text'], input[@type='file'], input[@type='hidden'], input[@type='password'], input[@type='submit'], option[@selected], textarea")
		.filter(":enabled")
		.each(function() {
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
		});
		$("body").addClass("curWait");

		$.post(this.getAttribute("action") + "?call=ajax", params, function(xml){
			$("body").removeClass("curWait");
			strError = "Unable to submit form. Please try again later.";
			oFocus = null;

			strRedirect = $('#redirecturl', $(xml)).text();
			strError = $('#error', $(xml)).text();
			strMsg = $('#msg', $(xml)).text();
			msgDiv = $('#msgdiv', $(xml)).text();
			oFocus = $('#focus', $(xml)).text();

			if (strError.length > 0) {
				var reg = new RegExp('(\|)(.+)', 'g');
				$("div.formErrors").html("<h3>Error<\/h3><ul><li>" + strError.replace(reg, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal");
			} else {
				if (strError.length == 0 && strRedirect.length > 0) {
					window.location = strRedirect;
				}
				if (strMsg.length > 0 && msgDiv.length > 0) {
					$("div."+msgDiv).html("<ul><li>" + strMsg.replace(reg, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal");
				}
			}
			if (oFocus) $("#" + oFocus).get(0).focus();

		});
		return false;
	});

	return this;
}
/* example: <AjaxResponse error="&#9;Password is a reqiured field.&#10;&#9;Name is a reqiured field.&#10;&#9;Location is a reqiured field.&#10;" focus="pwdAccountPassword" redirecturl="formSubmissionSuccess.php" /> */

/*$.fn.highQualityImage = function(lowSrc, highSrc){ 
  thisObject = $(this);
	
  thisObject.css('background-image', 'url('+lowSrc+')');
	
  return this.each(function(){ 
    var i = new Image(); 
    i.src = highSrc; 
    $(i).hide();
    thisObject.after(i);
    i.onload = function() {
    	thisObject.css('background-image', 'url('+highSrc+')');
    }; 
  }); 
} */

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 setBackgroundColor(id, background) {
	setTimeout('$("#'+id+'").css("background-color", "'+background+'")', 50);
}

/*--------------------------- on ready --------------------------*/

function changeSort(select) {
	var sort = $(select).val();
	
	if (sort == 0) {
		sort = '';
	} else if(sort.indexOf(' ') != -1) {
		sort = 'sort:'+sort.substr(0, sort.indexOf(' '))+'/'+'direction:'+sort.substr(sort.indexOf(' ') + 1);
	} else {
		sort = 'sort:'+sort;
	}
	
	var currentLocation = location.href;
	
	var reg = new RegExp('http://([^/]*)/');
	currentLocation = currentLocation.replace(reg, '/');
	var reg = new RegExp('(sort:[^/]*)');
	currentLocation = currentLocation.replace(reg, '');
	var reg = new RegExp('(direction:[^/]*)');
	currentLocation = currentLocation.replace(reg, '');
	var reg = new RegExp('\/\/', 'g');
	currentLocation = currentLocation.replace(reg, '/');
	
	if (currentLocation[currentLocation.length - 1] != '/') {
		currentLocation += '/';
	}

	location.href = currentLocation+sort;
}

/*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;
}*/


//---------------

var cghub = new Object();

cghub.url = {};
cghub.url.removeParams = function(url) {
	var reg = new RegExp('https?://([^/]*)/');
	url = url.replace(reg, '/');
	
	var reg = new RegExp('([^/]+:[^/]+)');
	url = url.replace(reg, '');
	
	var reg = new RegExp('/\?.*/');
	var getParams = url.replace(reg, ''); //???
	url = url.replace(getParams, '');
	var reg = new RegExp('\/\/', 'g');
	url = url.replace(reg, '/');
	
	return url;
};
cghub.url.current = function(removeParams) {
	var currentLocation = document.location.href;
	
	if (typeof removeParams == 'undefined') {
		var removeParams = true;
	}
	
	if (removeParams) {
		return cghub.url.removeParams(currentLocation);
	} else {
		return currentLocation;
	}
};
cghub.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];
	}
};
cghub.url.changeNamedParam = function(url, name, value) {
	var currentValue = cghub.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;
		}
	}
};




cghub.invalidateFields = function(fields){
	$('.error-message').remove();
	
	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]+']';
			}
			//console.log(name);
			
			var validInputTypes = ["submit", "reset", "radio", "password", "image", "file", "checkbox", "button", "text"];
			var inputSelector = '';
			validInputTypes.foreach(function(key, value){
				inputSelector += 'input[@name="'+name+'"][type="'+value+'"],';
			});
			
			invalidate(inputSelector+'textarea[@name="'+name+'"],select[@name="'+name+'"]', fields[field]);
		} else {
			//@todo
		}
	}
}

cghub.tree = {
	'moveElementData': {'from':{'pk':0,'name':''}, 'to':{'pk':0,'name':''}}
};

cghub.tree.moveElement = function(pk, name, moveUrl) {
	//last slash
	if (moveUrl.charAt(moveUrl.length - 1) != '/') {
		moveUrl += '/';
	}

	if (cghub.tree.moveElementData.from.name == '') {
		if (pk == 0) {
			return;
		}
		cghub.tree.moveElementData.from = {'pk':pk, 'name':name};
		alert("You have selected '"+name+"' element to move.\n Now select destination element.");
	} else if (cghub.tree.moveElementData.to.name == '') {
		cghub.tree.moveElementData.to = {'pk':pk, 'name':name};
		var res = confirm("Move element '"+cghub.tree.moveElementData.from.name+"' to '"+cghub.tree.moveElementData.to.name+"'?");
		if (res) {
			moveUrl += cghub.tree.moveElementData.from.pk+'/'+cghub.tree.moveElementData.to.pk+'/';
			$.ajax({
				'url':moveUrl,
				'type':'GET',
				'dataType':'json',
				'success':function(response){
					if (response.result == 'success') {
						cghub.refreshPage(true);
						//document.location.reload(false);
					} else {
						alert(response.message);
					}
				},
				'cache':false
			});
		}
		cghub.tree.moveElementData = {'from':{'pk':0,'name':''}, 'to':{'pk':0,'name':''}}; //empty
	}
};


cghub.user = {
	'id':null,
	'avatarUrl': {
		'large':null,
		'thumb':null
	}
};

cghub.user.liveAvatarUrl = function() {
	if (cghub.user.id === null || cghub.user.avatarUrl.thumb === null || cghub.user.avatarUrl.large === null) {
		return false;
	}
			
	$('img[@longdesc^="avatar_'+cghub.user.id+'_"]').each(function(){
		if (this.src.indexOf('thumb') != -1) {
			this.src = cghub.user.avatarUrl.thumb;//+'?_='+Math.random();
		} else {
			this.src = cghub.user.avatarUrl.large;//+'?_='+Math.random();
		}
	});
};

$(function(){
	var cookie = readCookie('liveAvatarUrl');
	if (cookie == null) {
		return false;
	}
	
	cookie = JSON.parse(unescape(cookie));
	
	cghub.user.id = cookie.id;
	cghub.user.avatarUrl = cookie.avatarUrl;
	
	cghub.user.liveAvatarUrl();
})