// Get URL Params
function gup(name) {
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var tmpURL = window.location.href;
	var results = regex.exec( tmpURL );
	if( results == null )
		return "";
	else
		return results[1];
}

// ELLIPSIS
//document.write('<style type="text/css">' +  '.ellipsis { margin-right:-10000px; }</style>');

function TextMetrixWidth(el) {
	var Styles = Array('font-size','font-style', 'font-weight', 'font-family','line-height');
	for (var i=0; i<Styles.length; i++) {
		$('#textmetrixdiv').css(Styles[i], $(el).css(Styles[i]));
	}
	parent.document.getElementById('textmetrixdiv').innerHTML =  $(el).attr('value');
	
	//$('#textmetrixdiv').text($(el).attr('value'));
	//console.log( parent.document.getElementById('textmetrixdiv').offsetWidth);
	return parent.document.getElementById('textmetrixdiv').offsetWidth;
}


$(document).ready(function(){
//
// Text Metrix Div
//
	var x = parent.document.createElement('div');
	$(x).css('position','absolute').css('left','-10000px').css('top','-10000px').css('height','auto').css('width','auto').attr('id', 'textmetrixdiv');
	parent.document.body.appendChild(x);

});


function replaceFormButtons(context) {
	$('.formbutton', context).each(function(){
		$(this).removeClass('formbutton');
		//alert(context);
		var BtnTable = document.createElement('table');
		var BtnTableRow = BtnTable.insertRow(0);
		var LeftBtnCell = BtnTableRow.insertCell(0);
		var CenterBtnCell = BtnTableRow.insertCell(1);
		var RightBtnCell = BtnTableRow.insertCell(2);
		var newBtnContainer = document.createElement('em');
		var newBtnSideLContainer = document.createElement('i');
		var newBtnSideRContainer = document.createElement('i');

		newBtnContainer.setAttribute('uselectable', 'on');

		$(newBtnSideLContainer).append(' ');
		$(newBtnSideRContainer).append(' ');

		$(BtnTable)
			.addClass('xBtn')
			.attr('title', $(this).attr('value') || '')
			.hover(
				function(){
					if ($('button:enabled', $(BtnTable)).length) $(this).addClass('xBtn-over');
				},
				function(){
					$(this).removeClass('xBtn-over');
					$(this).removeClass('xBtn-click');
				}
			)
			.mousedown(function(){
				//$(newBtn).focus();
				$(this).addClass('xBtn-click');
			})
			.mouseup(function(){
				$(this).removeClass('xBtn-click');
			});

		$(LeftBtnCell).addClass('xBtn-Left').append(newBtnSideLContainer);
		$(RightBtnCell).addClass('xBtn-Right').append(newBtnSideRContainer);


		var xBtnClasses = this.className.split(' ');
		var hasIco = $(this).hasClass('ico');
		var icoClassName = '';
		for (var i = 0; i < xBtnClasses.length; i++ ) {
			if (xBtnClasses[i].toString().match(/ico-\w+/)) icoClassName = xBtnClasses[i].toString();
		}

		if (hasIco && icoClassName) {
			$(this).removeClass('ico').removeClass(icoClassName)
		}

		$(CenterBtnCell).append(newBtnContainer).addClass(this.className);
		$(CenterBtnCell).addClass('xBtn-Center');
		
		var onClickEv = $(this).attr('onclick');

		if (jQuery.isFunction(onClickEv)) {
			$(BtnTable).bind('click', function(e){
				onClickEv();
			});
		} else if ( this.type == 'submit' ) {
			$(BtnTable).bind('click', function(e){
				if ($(this).find('button').length) {
					var f = $(this).find('button')[0];
					f.click();
				}
			});
		}
		
		$(this).hide().before(BtnTable);
		var Btn = '<button ' +
			'type="' +	($(this).attr('type') || 'button') +	'" ' +
			'id="' +	this.id +	'" ' +
			'class="' +	((hasIco && icoClassName) ? 'xBtn-text-ico ico ' + icoClassName : 'xBtn-text') + (($(this).attr('disabled')) ? ' disabled"' : '') + '" ' +
			(($(this).attr('disabled')) ? 'disabled="disabled"' : '') +
			'name="' +	$(this).attr('name')   +	'" ' +
			'title="' +	$(this).attr('title')   +	'" ' +
			(($(this).attr('jframe')) ? 'jframe="' + ($(this).attr('jframe') + '" ') : '') +
			'style="' +	(($(this).attr('value') == '') ? 'width:16px;' : '')   +	'" ' +
			'>' + $(this).attr('value') +
			'</button>';
		
		try {
			$(newBtnContainer).html(Btn);// = Btn;
			if ($(this).attr('value') != '') {
				if ($.browser.msie) {
					if ($(CenterBtnCell).width()) {
						$(CenterBtnCell).find('button').css('width', ($(CenterBtnCell).width()) + 'px');
					} else {
						$(CenterBtnCell).find('button').css('width', TextMetrixWidth(this) + 10 + 'px');
					}
				} else {
					if ($(CenterBtnCell).width()) {
						$(CenterBtnCell).find('button').css('width', ($(CenterBtnCell).width()) + 'px');
					} else {
						$(CenterBtnCell).find('button').css('width', TextMetrixWidth(this) + 22 + 'px');
					}
				}
			} else {
				$(CenterBtnCell).find('button').css('width',  '16px');
				//$(CenterBtnCell).find('button').css('background-position', 'center');
				/*if ($(CenterBtnCell).width()) {
					$(CenterBtnCell).find('button').css('width', ($(CenterBtnCell).width()) + 'px');
				} else {
				}*/
			}
		} catch (e) {alert(e.description)}
		$(this).remove();
	});
}

function parseTables(context) {
	$('.xTable td.chkbox', context)
		.parent()
		.filter(':not(.th)')
		.each(function(){
			$(this).addClass('cursor-hand');
		});

	$('.xTable tr', context)
		.filter(':has(:checkbox:checked):not(.th):not(.skip)')
		.addClass('selected')
		.end()
		.filter(':not(.th):not(.skip)')
		.filter(':has(:checkbox):not(.th)')
		.click(function(event) {
			if (event.target.tagName !='TD' && event.target.type !== 'checkbox') {

			} else {
				$(this).toggleClass('selected');
				if (event.target.type !== 'checkbox') {
					$(':checkbox', this).attr('checked', function() {
						return !this.checked;
					});
				}
			}
		});

	$('.filterBox', context).each(function(){
		$el = $(this);
		var mark = document.createElement('div');
		$(mark).addClass('filterBoxMark');
		$el.after($(mark));
	});
}


function messageReaded(el){
	$(el).removeClass('unread');
	$(el).parent().parent().removeClass('new');
	$("td:nth-child(2)",$(el).parent().parent()).html("<div class=\"ico-center ico-readed\" title=\"Read message\"/>");
}

$(function(){

	replaceFormButtons(document);
	parseTables(document);

/*	$('input.text, textarea.text').each(function(){ 
		//$(this).addClass('readonly');
		//console.log('readonly = ', this);
	});
	*/
	$('input[disabled], textarea[disabled]').each(function(){ 
		$(this).addClass('disabled');
	});

	$('input,textarea').parent().find('.limitation').parent().find('input,textarea')
		.filter(':not([readonly])')
		.each(function(){
			var transerentKeyCodes = [34,33,35,36,37,38,39,40,46];
			var transerentKeys = [8,13];
			var padWidth = 40;
			var max = parseInt($(this).attr('maxlength'));
			if (max && max > 0) {
				//var limCounter = document.createElement('span');
				var text = (this.type == 'text') ? $(this).val(): this.value;
				var length = text.length;
	
				/*$(this).after(limCounter);
				$(limCounter).addClass('limCounter').html(length + "<br>" + max);
				if (this.type == 'text') {
					$(limCounter).addClass('limInputBg');
				} else {
					$(limCounter).addClass('limTextareaBg');
					$(this).parent().find('.limitation').css('margin-top', '5px');
    			}*/
				$(this).parent().find('.limitation').html(length + " из " + max + " символов");					
				$(this)
					//.css('padding-right', padWidth + 'px')
					.css('position','relative')
					//.css('margin-right','40px')
					//.css('width', ($(this).width() - padWidth) + 'px')
					//.after(limCounter)

					.keyup(function(e){
						var text = (this.type == 'text') ? $(this).val(): this.value;
						var length = text.length;
						$(this).parent().find('.limitation').html(length + " из " + max + " символов");
						if (length > max) {
							if (this.type == 'text') {
								$(this).val(text.substr(0,max));
							} else {
								this.value = text.substr(0,max);
							}
						}
					})
					.keypress(function(e) {
						var sel = getSelection(this);
						var selected = sel.end - sel.start;
						var key = e.which;
						var keyCode = e.keyCode;
						var length = (this.type == 'text') ? $(this).val().length : this.value.length;
						var text = (this.type == 'text') ? $(this).val(): this.value;
						
						if (!selected && length >= max && !(($.inArray(key,transerentKeys)!=-1) || ($.inArray(keyCode,transerentKeyCodes)!=-1))) {
							e.preventDefault();
						}
					})
				.focus(function() {
						$(this)
							.parent()
							.find('.limitation')
				        	.show();
					})
					.blur(function() {
						$(this)
							.parent()
							.find('.limitation')
							.hide();
					})
			}
	});

	$('input[readonly].text').addClass('readonly').removeClass('text');

	$('#error_message_div').each(function(){
		var closeButton = document.createElement('div');
		$(closeButton)
			.addClass('closeButton ico ico-delete')
			.click(function(){
				$(this).parent().remove();
				$('.invalidfield').parent().find('p').remove();
				$('.invalidfield').removeClass('invalidfield');
			});
		$(this).prepend(closeButton);
	});

	$('.invalidfield')
		.parent()
		.find('p')
		.each(function(){
			$(this).addClass('errorP');
			$(this).parent().append(this);
		});
	
	$('select.invalidfield').filter(':not([multiline])').each(function(){
		el = $(this);
	});

	// recompile dissmiss alert link
	$('.alertDismiss')
		.each(function(){
			$(this)
				.attr('title', $(this).text())
				.attr('class','ico-right ico-deletesmall')
				.css('text-decoration', 'none')
				.text(' ');
		});

	/*
	 * new user messages table row are highlighted
	 * */
	$('.xTable a.unread').parent().parent().addClass('new');

	/*
	 * Adding filterboxMark
	 * */


	var currentFocus = null;
	$(':input').focus( function() {
		currentFocus = this;
	}).blur( function() {
		currentFocus = null;
	});


	$('.smplTable tr:odd').addClass('odd');

	$('.smplTable tr').hover(function(){
		if ($(this).hasClass('odd'))
			$(this).removeClass('odd').addClass('oddMarker');
		$(this).addClass('simpleTableOver');
	}, function(){
		if ($(this).hasClass('oddMarker'))
			$(this).removeClass('oddMarker').addClass('odd');
		$(this).removeClass('simpleTableOver');
	})

	$('.smplTable tr:last td').css('border-bottom', 'none')

})


function go(url){
   top.location.href = url;
   return false;
}



function browserCSS(){
	var body = $(document.body);
	if ($.browser.msie) $(body).addClass('msie');
	if ($.browser.safari) $(body).addClass('safari');
	if ($.browser.mozilla) $(body).addClass('mozilla');
	if ($.browser.opera) $(body).addClass('opera');
} 



$(function(){

	browserCSS()

	$('#help_link').click(function(){
      url = document.location.href.replace(base_url, '');
      url = base_url + 'helps/' + url;
      tb_show("Help", url + "?KeepThis=true&TB_iframe=true&height=400&width=500", false);
      return false;
   })


	/**
	 * Cookie
	 *
	 */

	jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

};
});

function truncate(text, length, ellipsis) {
	// Set length and ellipsis to defaults if not defined
	//if (typeof length == 'undefined') 
	var length = length || 30;
	//if (typeof ellipsis == 'undefined') 
	var ellipsis = ellipsis || '...';
	// Return if the text is already lower than the cutoff
	if (text.length < length) return text;
	//Otherwise, check if the last character is a space.
	// If not, keep counting down from the last character
	// until we find a character that is a space 
	//for (var i = length-1; text.charAt(i) != ' '; i--) {
	//	length--;
	//}
	// The for() loop ends when it finds a space, and the length var
	// has been updated so it doesn't cut in the middle of a word.
	return text.substr(0, length) + ellipsis;
}

$(function() {

	$('span.truncate').each(function(){
		var title = $(this).attr('title');
		var max_len = $(this).attr('max_len');
		$(this).html(truncate(title,max_len));
	});
});

function getSelection(el){
	var e = el.jquery ? el[0] : el;
	return (

		/* mozilla / dom 3.0 */
		('selectionStart' in e && function() {
			var l = e.selectionEnd - e.selectionStart;
			return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
		}) ||
	
		/* exploder */
		(document.selection && function() {
	
			e.focus();
	
			var r = document.selection.createRange();
			if (r == null) {
				return { start: 0, end: e.value.length, length: 0 }
			}
	
			var re = e.createTextRange();
			var rc = re.duplicate();
			re.moveToBookmark(r.getBookmark());
			rc.setEndPoint('EndToStart', re);
	
			return { start: rc.text.length, end: rc.text.length + r.text.length, length: r.text.length, text: r.text };
		}) ||
	
		/* browser not supported */
		function() {
			return { start: 0, end: e.value.length, length: 0 };
		}
	
	)();
		

}
