

$(document).ready(function()
{
	
	$('a.ajax-link-loading').click(function(e){
      $("#loading-ajax").fadeTo("slow", 0.66).css('left',(15+e.pageX)+'px').css('top',(15+e.pageY)+'px');
   	}); 

	
	
	// MSG
	$('div.flash-msg').effect("pulsate", { times:1 }, 500);


	// COUNT SELECT
	$('select.count').change( function() {
		window.location = $('option:selected', this).val();
	});

	
	// DELETE LINK CONFIRM
	$('a.delete-link').click( function() {
		return confirm('Czy na pewno chcesz usunąć?');
	});

	
	
	//TABLE BASIC ROW
	$('table.basic tr:even').addClass('even');
	$('table.basic tr:odd').addClass('odd');
	$('table.basic tr').hover( function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	
	
	
	//CLEAR FORM
    $('a.clear-form').click(function(){
    	var formId = $(this).attr('param');
    	
    	$('#'+formId).clearForm();
    	$('#'+formId).submit();
    	
    	return false;
    });
});




jQuery.fn.centerScreen = function(loaded) 
{
	var obj = this;
	if(!loaded) 
	{
	        obj.css('top', $(window).height()/2-this.height()/2);
	        obj.css('left', $(window).width()/2-this.width()/2);
	        $(window).resize(function() { obj.centerScreen(!loaded); });
	} else 
	{
	        obj.stop();
	        obj.animate({ top: $(window).height()/2-this.height()/2, left: $(window).width()/2-this.width()/2}, 200, 'linear');
	}
};




//------------------------------------------------------------------------------

function updateInfoInterval(dateFrom, days)
{
	$('div#info-date-interval').remove();
	
	if(0 == days)
	{
		$('div#wrap-active-to').show();
		return;
	}
	else if(100 == days)
	{
		$('div#wrap-active-to').hide();
		return;
	}
	else
	{
		$('div#wrap-active-to').hide();
	}
	
	if(null == dateFrom)
	{
		return;
	}
	
	//LICZYMY WŁĄCZNIE
	days = days - 1;
	
	var timeFrom = dateFrom.getTime();
	
	var dateTo = new Date();
	dateTo.setTime(timeFrom + (days * 24 * 60 * 60 * 1000));
	
	var month = dateTo.getMonth() + 1;
	if(month < 10)
	{
		month = '0'+month;
	}
	
	var day = dateTo.getDate();
	if(day < 10)
	{
		day = '0'+day;
	}
	
	
	var wrapElements = $('#active-interval').parents('div.wrap-elements:first');
	
	
	wrapElements.append('<div id="info-date-interval">Twoje oferta pozostanie aktywna do dnia: <strong>'
		+dateTo.getFullYear()+'-'+month+'-'+day+' do godziny 24:00</strong></div>');
	$('div#info-date-interval').effect("pulsate", { times:1 }, 500);
}

//------------------------------------------------------------------------------
function getDays(dateStart, dateEnd)
{
	var timeStart = dateStart.getTime();
	var timeEnd = dateEnd.getTime();
	
	var interval = timeEnd - timeStart;
	
	if(interval < 0)
	{
		return -1;
	}
	
	var tmpDate = new Date();
	tmpDate.setTime(interval);
	
	return (tmpDate/1000/60/60/24) + 1;
}





//------------------------------------------------------------------------------
function poAlert(content)
{
	/*
	$('<div></div').append(content).dialog({
					title:'Wiadomość',
					 buttons: { "Ok": function() { $(this).dialog("close"); } } 
	}).show();
	*/
	alert(content);
}

//------------------------------------------------------------------------------
function cacheAdd(namespace, name, value)
{
	var spaceVal = getNamespace(namespace);
	spaceVal[name] = value;
	 $("body").data(namespace, spaceVal);
}
function cacheGet(namespace, name)
{
	var spaceVal = getNamespace(namespace);
	return spaceVal[name];
}
function cacheRemoveNamespace(namespace)
{
	$("body").removeData(namespace);
}
function cacheRemove(namespace, name)
{
	var spaceVal = getNamespace(namespace);
	if(spaceVal[name])
	{
		delete spaceVal[name];
	}
	$("body").removeData(namespace);
	$("body").data(namespace, spaceVal);
}

function getNamespace(namespace)
{
	return $("body").data(namespace) == undefined ? {} : $("body").data(namespace);
}
//------------------------------------------------------------------------------






// AJAX-DETAILS TABLE
jQuery.fn.ajaxDetails = function(options) {

	var options = jQuery.extend( {url:""}, options);
	
	return this.each( function() {
		jQuery(this)
			.click(
				function() {
					
					if(jQuery(this).data('lock'))
					{
						return;
					}
					jQuery(this).data('lock', true);

					var id = jQuery(this).attr('rel');
					
					var uid = jQuery(this).data('uid');
					if(undefined == uid)
					{
						uid = new Date().getTime();
						jQuery(this).data('uid', uid);
					}
					
					
					//CZY WIDAC DETALE
					if(jQuery(this).data('show'))
					{
						
						//USUWAM
						jQuery("#uid-"+uid+"tr-" + id).remove();
						jQuery('img', this).attr('src',jQuery(this).attr('srcShow'));

						jQuery(this).data('show', false);
						jQuery(this).data('lock', false);
						return;
					}
					
					jQuery('img', this).attr('src',jQuery(this).attr('srcWait'));

					var colspan = jQuery(this).data('colspan');

					if(undefined == colspan)
					{
						colspan = jQuery(this).parents('tr:first').find('td').length;
						jQuery(this).data('colspan', colspan);
					}

					var thisR = this;


					// CLICK FAST
					jQuery("#uid-"+uid+"tr-" + id + " td").remove();

					var tr = jQuery('<tr id="uid-'+uid+'tr-' + id + '" ><td class="td-ajax" colspan="'+colspan+'" >Trwa pobieranie danych...</td></tr>');
					jQuery(this).parents('tr:first').after(tr);

					
					//IF EXIST CACHE
					var cache = cacheGet('offerTypeInfo', 'offerType'+id+''+uid);
					if(cache)
					{
						tr.find('td').html(cache);
						
						jQuery('img', this).attr('src',jQuery(this).attr('srcHide'));
						
						jQuery(this).data('show', true);

						jQuery(this).data('lock', false);
						
						return;
					}
					
					
					jQuery.ajax(
					{url:options.url,
					 beforeSend: function(){
					    $("#loading-ajax").show();
					   },
					   complete: function(){
					      $("#loading-ajax").hide();
					   },

						data:{'param' :id},
						
						success: function(response) {
							tr.find('td').html(response);

							jQuery('img', thisR).attr('src',jQuery(thisR).attr('srcHide'));

							//SAVE DATA
							cacheAdd('offerTypeInfo', 'offerType'+id+''+uid, response);
							
							jQuery(thisR).data('show', true);

							jQuery(thisR).data('lock', false);
							
							
						}
					});
				});

	});

};



/* zmiana statusu*/




	

jQuery.fn.ajaxChangeDialog = function(options) {

	var options = jQuery.extend( {url:"", namespace:""}, options);
	
	
	
	jQuery('body').append('<div id="dialog-link-'+options.namespace+'" style="display:none;"><div class="info"></div><div id="email"><p>Czy wysłaś powiadomienie:<br><input type="radio"  class="send" checked="checked" value="not-send" name="email" />Nie<br><input type="radio"  class="send" value="send" name="email" />Tak<br></p><form class="form" action="" method="POST">Temat:<br><input  style="width:95%;" type="text" class="subject" name="subject" value="" /><br>Treść:<br><textarea class="content" name="content" style="width:95%; height:100px;"></textarea><input type="hidden" name="url" class="url" /></form></div></div>');
	
	var rootDialog = jQuery('#dialog-link-'+options.namespace);
	
	//PO KLIKNIECIU W RADIO, FORM SIE WYSWIETLA
	jQuery('input.send', rootDialog).click(function(){

		if('send' == jQuery(this).val())
		{
			if(jQuery(this).attr('checked'))
			{
				jQuery('form.form', rootDialog).fadeTo('fast', 1);
			}
		}
		else
		{
			jQuery('form.form', rootDialog).fadeTo('fast', 0.3);
		}
	});
	
	
	return this.each( function() {
		jQuery(this)
			.click(
				function() {
					
					var param = jQuery(this).attr('param');
					
					var thisR = this;
					
					jQuery(this).parents('tr:first').addClass('dialog-highlight');
					
					
					//POBIERAM DANE
					jQuery.ajax({ 'url':options.url, data:{'param' :param},
						success: function(response) {
							
							$("#loading-ajax").hide();
							
							if(response.status != 'ok')
							{
								alert(response.message);
								jQuery('tr.dialog-highlight').removeClass('dialog-highlight');
							}
							else
							{
								jQuery('input.send:first', rootDialog).click();
								
								var parent = rootDialog;
								
								jQuery('div.info', parent).html(response.info);
								jQuery('form input.subject', parent).val(response.subject);
								jQuery('form textarea.content', parent).val(response.content);
								jQuery('form input.url', parent).val(jQuery(thisR).attr('href'));
								
								
								var dialog = parent.dialog({
												title:response.title,
												modal: true,
												autoOpen: false ,
												width: 460,
												bgiframe: true,
												buttons: {
												"Zmień status": function() {
							
													var url = jQuery.trim($('form input.url', parent).val());
													
														//JEZELI WYBRANO WYSLANIE EMAILA
														if('send' == $('input.send:checked', parent).val())
														{
															var subject = jQuery.trim($('form input.subject', parent).val());
															var content = jQuery.trim($('form textarea.content', parent).val());
															
															
															var isError = false;
							
															//if is sub and cont
															if(''==subject)
															{
																isError = true;
																alert('Wprowadź poprawny temat!')
															}
															else if(''==content)
															{
																isError = true;
																alert('Wprowadź poprawną treść!')
															}
							
															if(false == isError)
															{
																
																//WYSYLAM FORMA (POST)
																jQuery('form.form', parent).attr('action', url).submit();
																
															}
														}
														else
														{
															//BEZ WYSLANIA EMAILA, CZYLI ZWYKLA ZMIANA
															window.location = url;
															
														}
														
														jQuery(this).dialog("close");
														jQuery('tr.dialog-highlight').removeClass('dialog-highlight');
							
													},
												"Anuluj": function() {
							
													jQuery(this).dialog("close");
													jQuery('tr.dialog-highlight').removeClass('dialog-highlight');
													}
							
												}
									});
								dialog.dialog('option', 'title', response.title);
								dialog.dialog('open');
			
								//--------------
							}
							
						},
						dataType:'json',
					beforeSend: function(){
					    $("#loading-ajax").show();
					   },
					   complete: function(){
					      $("#loading-ajax").hide();
					   }
					
					});
					
					return false;
					
					/*click end*/
				});

	});

};





/* zmiana statusu*/















function str_replace(search, replace, subject) {
    var s = subject;
    var ra = r instanceof Array, sa = s instanceof Array;
    var f = [].concat(search);
    var r = [].concat(replace);
    var i = (s = [].concat(s)).length;
    var j = 0;

    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    }

    return sa ? s : s[0];
}


function explode( delimiter, string, limit ) {
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}



var WindowObjectReference = null; 
var PreviousUrl = null;


function openWindowUrl(strUrl)
{
	return window.open(strUrl, 'Window',
         "resizable=yes,width=950,height=500,scrollbars=yes,status=no,location=no,toolbar=no,'menubar=no,left=5,top=5");
}

function openUrl(strUrl)
{
	if(WindowObjectReference == null || WindowObjectReference.closed)
	{
		WindowObjectReference = openWindowUrl(strUrl);
	}
	else if(PreviousUrl != strUrl)
	{
		WindowObjectReference = openWindowUrl(strUrl);
	}
	
	WindowObjectReference.focus();
	
	PreviousUrl = strUrl;
}



