$.fn.getNonColSpanIndex = function() {
    if(! $(this).is('td'))
        return -1;

    var allCells = this.parent('tr').children();
    var normalIndex = allCells.index(this);
    var nonColSpanIndex = 0;

    allCells.each(
        function(i, item)
        {
            if(i == normalIndex)
                return false;

            var colspan = $(this).attr('colspan');
            colspan = colspan ? parseInt(colspan) : 1;
            nonColSpanIndex += colspan;
        }
    );

    return nonColSpanIndex;
};


var fixCellIndexes = function(table) {
	var rows = table.rows;
	var len = rows.length;
	var matrix = [];
	for ( var i = 0; i < len; i++ )
	{
		var cells = rows[i].cells;
		var clen = cells.length;
		for ( var j = 0; j < clen; j++ )
		{
			var c = cells[j];
			var rowSpan = c.rowSpan || 1;
			var colSpan = c.colSpan || 1;
			var firstAvailCol = -1;
			if ( !matrix[i] )
			{ 
				matrix[i] = []; 
			}
			var m = matrix[i];
			// Find first available column in the first row
			while ( m[++firstAvailCol] ) {}
			c.realIndex = firstAvailCol;
			for ( var k = i; k < i + rowSpan; k++ )
			{
				if ( !matrix[k] )
				{ 
					matrix[k] = []; 
				}
				var matrixrow = matrix[k];
				for ( var l = firstAvailCol; l < firstAvailCol + colSpan; l++ )
				{
					matrixrow[l] = 1;
				}
			}
		}
	}
};


// 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];
}

function tableColumns(tbl,context) {
	changeSelectAllHandle('columns-container-' + tbl);
	$('input[type=checkbox]:gt(1)', '#columns-container-' + tbl).click(function(){
		changeSelectAllHandle('columns-container-' + tbl);
	});
	$('#columns-container-' + tbl + ' input.disabled')
		.parent().parent()
		.find('label').css('color','#888');
}


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');
	return parent.document.getElementById('textmetrixdiv').offsetWidth;
}


$.fn.extend({
	guiDisable: function() {
		if ($(this).hasClass('guibutton')) $(this).attr('disabled', 'disabled').addClass('disabled');
	},
	guiEnable: function() {
		if ($(this).hasClass('guibutton')) $(this).attr('disabled', '').removeClass('disabled');
	},
	guiSetSelectedIndex: function(index){
		if ($(this).hasClass('guibutton'))  {
			// not implemented yet
		}
	},
	guiSetSelectedByValue: function(value){
		$('> u > i > a', this).removeClass('selected');
		$(this).each(function(){
			var selectedEl = $('> u > i > a[rel="'+ value +'"]', $(this));
			$('>b>b>b',this)[0]['oldOnClick'] = selectedEl[0].onclick;
			selectedEl.addClass('selected');
		})
	}
});

function bindOnClick() {
	return function(event) {
		 if($(this).closest('a,span').hasClass('disabled')) return false;
		 this['oldOnClick'].call(this, event || window.event);
		 return false;
	 };
}

function replaceFormButtons(context) {
	
	$('.guibutton[disabled]', context).addClass('disabled');
	$('.guibutton', context).each(function(i){
		if ($(this).hasClass('noremap') || $(this).hasClass('thickbox')) return false;
		var el = $('>b>b>b',this);
		if (typeof this.onclick == 'function') {
         if ('undefined' == typeof(el[0]['oldOnClick'])) {
			   el[0]['oldOnClick'] = this.onclick;
			   this.onclick = '';
			   el.bind('click', bindOnClick());
         }
		}
	});
	
	$('.guibutton', context)
		.hover(function(e){
			if ((e.target.tagName == 'SPAN' || e.target.tagName == 'A' || e.target.tagName == 'B') && (!$(this).hasClass('disabled')))
				$(this).addClass('over');
		}, function(){
			$(this).removeClass('over').removeClass('click');
		})
		.mouseup(function(){
			$(this).removeClass('click');
		})
		.mousedown(function(e){
			if (e.target.tagName == 'SPAN' || e.target.tagName == 'A' || e.target.tagName == 'B' )
				$(this).addClass('click');
		});
		

	$('.guibutton > u', context)
		.click(function(e){
			if ($('> i:visible', this).parents('.guibutton').length > 0) {
			} else {
				$('.guibutton > u > i').hide();	
				$('.guibutton > u').removeClass('click');
			}
			el = $('>i', this);
			el.css('margin-left', '-' + (el.width()-16) + 'px').toggle();
			if (el.length == 1) {
				$(this).addClass('click');	
			} else {
				$(this).removeClass('click');
			}
			e.stopPropagation();
		})
		.hover(function(e){
			$(this).addClass('over');
		}, function(e){
			$(this).removeClass('over');
		});
		
		$(document).click(function(e){
			$('.guibutton > u > i').hide();
			$('.guibutton > u').removeClass('click');
		});
}


function replaceErrors(context) {
	context = context || document;
	$('#error_message_div', context).each(function(){
		var closeButton = document.createElement('div');
		$(closeButton)
			.addClass('closeButton ico ico-delete')
			.click(function(){
				$(this).parent().hide();
				$('.invalidfield', context).parent().find('p').hide();
				$('.invalidfield', context).removeClass('invalidfield');
			});
		$(this).prepend(closeButton);
	});

	$('.invalidfield', context)
		.parent()
		.find('p')
		.each(function(){
			$(this).addClass('errorP');
			$(this).parent().append(this);
		});
	
	$('select.invalidfield', context).filter(':not([multiline])').each(function(){
		el = $(this);
	});
}


function parseTables(context) {
	if ($('.xTable', context).length == 0) return false;
	
	$('td.chkbox', context)
		.parent(':not(.th, .pagetotal, .alltotal)')
		.addClass('cursor-hand');
	
	$('td.chkbox:has(:checkbox:checked)', context)
		.parent().addClass('selected');
	
	$('.xTable>tbody>tr:not(.th)', context)
		.click(function(event) {
			if ($('>td.chkbox:has(:checkbox)', this).length > 0) {
				if ($(event.target.offsetParent).hasClass('xTable') || event.target.type == 'checkbox') {
					if (event.target.tagName !='TD' && (event.target.type != 'checkbox' || !($(event.target).parent().hasClass('chkbox')))) {
					} else {
						if (!$(event.target).parents().filter('tr').find('.chkbox :checkbox:disabled').length) {
							$(this).toggleClass('selected');
							if (event.target.type !== 'checkbox') {
								$(':checkbox:eq(0)', this).attr('checked', function() {
									return !this.checked;
								});
							}
						}
					}
				}
			}	
		});

	$('.filterBox', context).each(function(){
		$el = $(this);
		var mark = document.createElement('div');
		$(mark).addClass('filterBoxMark');
		$el.after($(mark));
	});


	/* ***************** COLUMN SELECTION ****************** */

	var className = 'curColumn';
	
	$('.xTable > tbody > tr.th > td:not(.simpleTitle, .nohl)[onclick]', context).addClass('cursor-hand').hover(function() {
		var index = $.browser.safari ? $(this).parent().children().index(this) : this.cellIndex;
		var selector = '> tr:not(.th) > td:not(.nodata):nth-child('+ (index + 1) +')'; 
		$(selector , $(this).parent().parent()).addClass(className);
	},
	function() {
		var index = $.browser.safari ? $(this).parent().children().index(this) : this.cellIndex;
		var selector = '> tr:not(.th) > td:not(.nodata):nth-child('+ (index + 1) +')'; 
		$(selector , $(this).parent().parent()).removeClass(className);
	});

	
	
	$('.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');
	
	$('.xTable tr td.border_left').prev().css('border-right', 'none');
	
	$('.xTable>tbody>tr:first-child, .xTable>tbody>tr>td:first-child').addClass('first');
	$('.xTable>tbody>tr:last-child, .xTable>tbody>tr>td:last-child').addClass('last');
	
}

/* ***************** /COLUMN SELECTION ****************** */

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 jFrameGUI(id){
	context = $('#' + id).get(0);
	replaceFormButtons(context);
	replaceErrors(context);
	parseTables(context);
}

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 limitation() {
	$('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)
				//.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('.limCounter').html(length + "<br>" + 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();
				})
		}
	});
}


$(function(){
	// textmetric
	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);
	
	browserCSS();
	limitation();
	replaceFormButtons(document.body);
	replaceErrors(document.body);
	parseTables(document.body);
	
	// css issues for buttons
	
	$('.button')
		.hover(function(){
			$(this).addClass('buttonHover');
		}, function(){
			$(this).removeClass('buttonHover');
			$(this).removeClass('buttonPress');
		})
		.mousedown(function(){
			$(this).addClass('buttonPress');
		})
		.mouseup(function(){
			$(this).removeClass('buttonPress');
		})
	

/*	$('input.text, textarea.text').each(function(){ 
		//$(this).addClass('readonly');
	});
	*/

	$('input[disabled], textarea[disabled]').each(function(){ 
		$(this).addClass('disabled');
	});

	$('input[readonly].text').addClass('readonly').removeClass('text');

	// remove ���
	$('.alertDismiss').text('').hide().remove();
	// 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;
	});

})


function go(url){
   top.location.href = url;
   return false;
}

$(function(){

	$('#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 };
		}
	
	)();
}

function toggleContainer(id) {
	$('#' + id).toggle();
	$('#' + id).css('margin-top', '21px');
	$('#' + id).css('margin-left', '-' + ($('#' + id).width() - 150 + 24 ) + 'px');
	return false;
}

function toggleAdsBlock(id, mode) {
   /*var x = $('#bulk-editor-container:visible');
	if (x.length == 1) return false;
*/
   if ('show' == mode) {
	   
      $('#' + id).addClass('grayed');
      $('.ad-edit-handle', '#' + id).show();
   } else {
      $('#' + id).removeClass('grayed');
      $('.ad-edit-handle', '#' + id).hide();
   }
   return false;
}

function showBulkEditor(code) {
   // Start Loading
   startBulkLoading();
   // Show Container
   showBulkContainer(code);
   jQuery.ajaxSetup({
      async: false,
      cache: false
   });
   
    
   jQuery.get(site_url + 'index.php/advertiser/manage_ads_ads/get_ad_info/' + code, function(data) {
      if(!checkAjaxLogin(data)) {
         eval('data = ' + data);
         // Hide unnecessary fileds
         if ('text' == data.ad_type) {
            jQuery('.text_only', '#bulk-editor-container').show();
         } else {
            jQuery('.text_only', '#bulk-editor-container').hide();
         }
         // Fill fields
         jQuery('#bulk_ad_code', '#bulk-editor-container').val(code);
         jQuery('#bulk_ad_type', '#bulk-editor-container').val(data.ad_type);
         jQuery('#bulk_ad_title', '#bulk-editor-container').val(data.title);
         jQuery('#bulk_ad_description1', '#bulk-editor-container').val(data.description1);
         jQuery('#bulk_ad_description2', '#bulk-editor-container').val(data.description2);
         jQuery('#bulk_ad_display_url', '#bulk-editor-container').val(data.display_url);
         jQuery('#bulk_ad_destination_url', '#bulk-editor-container').val(data.destination_url);
         jQuery('#bulk_ad_destination_protocol', '#bulk-editor-container').val(data.destination_protocol);
         // Show preview
         UpdateTextPreview();
         // Stop Loading
         stopBulkLoading();
      }
   })
   jQuery.ajaxSetup({
      async: true,
      cache: true
   });
   return false;
}

function startBulkLoading() {
   jQuery('#error_message_div', '#bulk-editor-container').hide();
   jQuery('.errorP', '#bulk-editor-container').hide();
   jQuery('.invalidfield', '#bulk-editor-container').removeClass('invalidfield');
   jQuery('#bulk-editor-container .filterBox').addClass('loading-big').find('.table').css('visibility', 'hidden');
}

function stopBulkLoading() {
   jQuery('#bulk-editor-container .filterBox').removeClass('loading-big').find('.table').css('visibility', 'visible');
}

var lastcode = ''
function showBulkContainer(code) {
		
	if (code == lastcode) {
		$('#bulk-editor-container').show();
	} else {
		inp = $('input[value='+code+']').before($('#bulk-editor-container'));
		$('#bulk-editor-container').css('margin-left', '40px').css('margin-top', '-40px').css('text-align', 'left').show();
	}
	lastcode = code;
}

function hideBulkContainer() {
   jQuery('#bulk-editor-container').hide();
   jQuery('#error_message_div', '#bulk-editor-container').hide();
   jQuery('.errorP', '#bulk-editor-container').hide();
   jQuery('.invalidfield', '#bulk-editor-container').removeClass('invalidfield');
}

function reloadDinamicFrame(tab) {
   jQuery('#dinamic').loadJFrame(jQuery('#dinamic').attr('src'), function(){tabs_click(tab)});
}

function onDisplayUrlChange(prefix) {
   if($('#'+prefix+'_display_url').val() != '') {
      if($('#'+prefix+'_destination_url').val() == '') {
         $('#'+prefix+'_destination_url').val($('#'+prefix+'_display_url').val());
         $('#'+prefix+'_destination_url').trigger('onkeyup');
      }
   }
   
}

/**
* IE hacks
*/
if(!Array.indexOf) {
  Array.prototype.indexOf = function(obj) {
     for (var i = 0; i < this.length; i++) {
        if (this[i] == obj) {
           return i;
        }
     }
     return -1;
  }
}

Array.prototype.remove = function(from, to) {
   var rest = this.slice((to || from) + 1 || this.length);
   this.length = from < 0 ? this.length + from : from;
   return this.push.apply(this, rest);
};


function select_all(table, obj) {
	if (obj.checked) {
	   $('> tr[id] > td.chkbox > input:checkbox:enabled', $(obj).parent().parent().parent())
	   	.attr('checked', 'checked')
	   	.parent()
	   	.parent()
	   	.addClass('selected');
	   
   } else {
	   $('> tr[id] > td.chkbox > input:checkbox:enabled', $(obj).parent().parent().parent())
	   	.attr('checked', '')
	   	.parent()
	   	.parent()
	   	.removeClass('selected');
   }
   return true;
}

/**
 *  Popup Editors
 */

function hookDocumentClick(popup_id, caller_class, hide_effect) {
	$(document).click(function(e){
	    if (($(e.target).parents().filter('#'+popup_id+':visible').length != 1) && 
	    	  ($(e.target).parents().filter('#'+popup_id).length != 1)) {
	    	   if ($(e.target).hasClass(caller_class)) {
	    		    $(e.target).removeClass(caller_class);
	    		    return;
			   } else {
			    	  if ($('#'+popup_id+':visible').length > 0) {
			    		  hide_effect = hide_effect || undefined;
			    		   if (hide_effect) {    
			    		        $('#' + popup_id).fadeOut(hide_effect);
			    		    } else {
			    		       $('#' + popup_id).hide();
			    		    }
			        }
			   }
	    }
});	
}

function showContainer(popup_id, caller, effect) {

	effect = effect || undefined;
	$('#' + popup_id).hide();
	//get the position of the placeholder element  
	var pos = $(caller).offset();    
	var eWidth = $(caller).outerWidth();
	var mWidth = $('#'+popup_id).outerWidth();
	var left = (pos.left + eWidth - mWidth) + "px";
	var top = pos.top + "px";
    
	  //show the menu directly over the caller
	$('#' + popup_id).css({ 
		position: 'absolute',
		zIndex: 5000,
		left: left, 
		top: top
	});

	if (effect) {	  
		$('#' + popup_id).fadeIn(effect);
	} else {
		$('#' + popup_id).show();
	}
	return false;
}

function hideContainer(popup_id, effect) {
	effect = effect || undefined;
	if (effect) {    
        $('#' + popup_id).fadeOut(effect);
    } else {
       $('#' + popup_id).hide();
    }
    return false;
}

function createMail(code, role) {
   codeForm = '<form id="send_mail_form" method="post" action="' + site_url + 'admin/mail/index/' + role + '">';
   codeForm += '<input type="hidden" name="post_mail_targets" value="' + code + '" />';
   codeForm += '</form>';
   $('body').append(codeForm);
   $('#send_mail_form').submit();
   return false;
}
