var url_variable = 'http://biteo.pl/';


/*	When document is full loaded (ready) init
 *  dom element's behaviours and animations 
 */

var dtCh= "-";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	
	if (s == null)
		return false;
	
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strDay=dtStr.substring(pos2+1)
	var strYear=dtStr.substring(0,pos1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
return true
}

function createDistinctionRow(i, data){
	var heading = $('#distinction_list thead').css('display');
	if (heading == 'none') {
		 $('#distinction_list thead').show();
	}	    	
    var tr = $('<tr></tr>').addClass('dataRow');
    var td1 = $('<td></td>').addClass('first').html((i+1)+'<input class="id_distinction" type="hidden" value="'+ data.id_distinction +'" />' );
    var td2 = $('<td></td>').html(data.distinction_name);
    var td3 = $('<td></td>').html('<div class="start_date" id="start_date_'+i+'">' + data.start_date + '</div>');
    var td4 = $('<td></td>').html('<div class="end_date" id="end_date_'+i+'">' + data.end_date + '</div>');
    var td5 = $('<td></td>').html((data.active == 1 ? 'aktywna' : 'historyczna'));
    var td6 = $('<td></td>').html('<span class="distinction_price"  id="distinction_offer_cost_'+i+'">'+parseFloat(data.cost).toFixed(2) + '</span><input type="hidden" id="distinction_offer_payed_'+i+'" value="'+(data.payed == 1 ? data.cost : 0)+'" /><input type="hidden" id="distinction_cost_'+i+'" value="'+data.distinction_cost+'" />');
    var td7 = $('<td></td>').html(' <strong><a href="javascript: void(0);" class="removeDistinction" title="'+i+'">usuń</a></strong> <strong><a href="javascript: void(0);" class="editDates" title="'+i+'">edytuj</a></strong>');
    $(tr).append(td1);
    $(tr).append(td2);
    $(tr).append(td3);
    $(tr).append(td4);
    $(tr).append(td5);
    $(tr).append(td6);
    $(tr).append(td7);
    return tr;
}

function createDistinctionRowEdt(i,data) {
	var heading = $('#distinction_list_edit thead').css('display');
	if (heading == 'none') {
		 $('#distinction_list_edit thead').show();
	}	    
    var tr = $('<tr></tr>').addClass('dataRow');
    var td1 = $('<td></td>').addClass('first').html((i+1)+'<input class="id_distinction" type="hidden" value="'+ data.id_distinction +'" /><input type="hidden" name="distinction_offer_id_'+i+'" value="'+data.distinction_offer_id+'" />' );
    var td2 = $('<td></td>').html(data.distinction_name);
    var td3 = $('<td></td>').html('<div class="start_date" id="start_date_'+i+'">' + data.start_date + '</div>');
    var td4 = $('<td></td>').html('<div class="end_date" id="end_date_'+i+'">' + data.end_date + '</div>');
    var td5 = $('<td></td>').html((data.active == 1 ? 'aktywna' : 'historyczna'));
    var td6 = $('<td></td>').html('<span class="distinction_price"  id="distinction_offer_cost_'+i+'">'+parseFloat(data.cost).toFixed(2) + '</span><input type="hidden" id="distinction_offer_payed_'+i+'" value="'+(data.payed == 1 ? data.cost : 0)+'" /><input type="hidden" id="distinction_cost_'+i+'" value="'+data.distinction_cost+'" />');
    var td7 = $('<td></td>').html((data.active == 1 && data.begun == 0 ? ' <strong><a href="javascript: void(0);" class="removeDistinction" title="'+i+'">usuń</a></strong> <strong><a href="javascript: void(0);" class="editDates" title="'+i+'">edytuj</a></strong>' : '') + (data.active == 1 && data.begun == 1 ? '<strong><a href="javascript: void(0);" class="editEndDate" title="'+i+'">edytuj</a></strong>' : ''));
    $(tr).append(td1);
    $(tr).append(td2);
    $(tr).append(td3);
    $(tr).append(td4);
    $(tr).append(td5);
    $(tr).append(td6);
    $(tr).append(td7);
    return tr;
}

function createErrorRow(i){
    var tr = $('<tr></tr>').addClass('hiddenErrorBox_'+i).hide();
    var td1 = $('<td colspan="2"></td>').addClass('bottomErrorBoxLeft');
    var td2 = $('<td colspan="5"></td>').addClass('error_'+i).addClass('bottomErrorBox');
    $(tr).append(td1);
    $(tr).append(td2);
    return tr;
}

function createDisctinctionSummary() {
    var sum = 0.0;
    var i = 0;
    $('table#distinction_list tbody tr.dataRow').each(function(){
        sum+=parseFloat($(this).children('td').next('td').next('td').next('td').next('td').next('td').children('span.distinction_price').html());
        i++;
    });
    if (i > 0) {
        $('#summary_label').html('Podsumowanie');
        return sum + ' zł';
    }else {
        $('#summary_label').html('');
        return '';
    }
}

function createDisctinctionSummaryEdt() {
    var sum = 0.0;
    var i = 0;
    var paid = 0.0;
    var paidHtml;
    var sumHtml;
    $('table#distinction_list_edit tbody tr.dataRow').each(function(){
        sumHtml = $(this).children('td').next('td').next('td').next('td').next('td').next('td').children('span.distinction_price').html();
        if (sumHtml != null)
          sum+=parseFloat(sumHtml);
        paidHtml = $(this).children('td').next('td').next('td').next('td').next('td').next('td').children('input').val();
        if (paidHtml != null)
          paid+=parseFloat(paidHtml);
        i++;
    });
    if (i > 0) {
        $('#summary_label').html('Podsumowanie');
        $('#paid_label').html('Zapłacono');
        $('#paid_summary').html(paid+' zł');
        $('#to_pay_label').html('Pozostało do zapłaty');
        $('#to_pay_summary').html(parseFloat(sum-paid)+' zł');
        return sum + ' zł';
    }else {
        $('#summary_label').html('');
        $('#paid_label').html('');
        $('#paid_summary').html('');
        $('#to_pay_label').html('');
        $('#to_pay_summary').html('');            
        return '';
    }
}


$(document).ready(function(){
	
	var jsNewPrice = parseFloat($('.inputHiddenPriceJs').val());
	var jsPriceActual;
	var thisPriceJs;
	
	
	/*
	$("#uploadify").uploadify({
		'uploader'       : 'http://fs0000/lib/uploadify.swf',
		'script'         : 'http://fs0000/lib/uploadify.php',
		//'checkScript'    : '',
		'scriptAccess'   : 'always',
		//'cancelImg'      : 'cancel.png',
		'folder'         : '/storage/temp',
		'queueID'        : 'fileQueue',
		'auto'           : true,
		'multi'          : true
	});
	*/
	
	// miniatury ikon ofert
	// 
	$("a.image-icon").hover(
	function(e){
		// wysokosc wyswietlanej miniatury
		var thumbHeight = 250;

		// style miniatury
		var thumbStyle = "position:absolute;border:1px solid #ccc;background:#333;padding:5px;display:none;color:#fff;z-index:1000;";		
		
		// wysokosc niewiedocznej czesci dokumentu (od gory) 
		var scroll = $(window).scrollTop();

		// wysokosc widocznej czesci dokumentu
		// warunek dla IE
		var winHeig = window.innerHeight;
		if (!winHeig) winHeig = document.documentElement.clientHeight;
		
		// przesuniecie miniatury wzgledem elementu uruchamiajacego
		var xOffset,yOffset = 70;
		
		// pozycja elementu uruchamiajacego wzgledem dokumentu
		var off = $(this).offset();
		
		// odleglosc elementu uruchamiajacego od dolnej krawedzi
		var space = scroll + winHeig - off.top;
		
		// przesuniecie minitaury w zaleznosci od wolnego miejsca
		// mozliwe 3 pozycje (ponizej, wycentrowane i powyzej)
		if(space > thumbHeight) xOffset = 0;//parseInt(linkHeight/2);
		else if(space < parseInt(thumbHeight/2)) xOffset = thumbHeight;
		else xOffset = parseInt(thumbHeight/2);
		
		this.t = this.title;
		this.title = "";
		$("body").append("<p id='screenshot' style='" + thumbStyle + "'><img src='"+ this.rel +"' /></p>");								 
		$("#screenshot")
			.css("top",(off.top - xOffset) + "px")
			.css("left",(off.left + yOffset) + "px")
			.fadeIn("fast");
	},
	function(){
		this.title = this.t;	
		$("#screenshot").remove();
    });	
	
	// miniatury plikow graficznych demo
	//
	$("a.demo-thumb").hover(
			function(e){
				// wysokosc wyswietlanej miniatury
				var thumbHeight = 300;

				// style miniatury
				var thumbStyle = "position:absolute;border:1px solid #ccc;background:#333;padding:5px;display:none;color:#fff;z-index:1000;";
				
				// wysokosc niewiedocznej czesci dokumentu (od gory) 
				var scroll = $(window).scrollTop();

				// wysokosc widocznej czesci dokumentu
				// warunek dla IE
				var winHeig = window.innerHeight;
				if (!winHeig) winHeig = document.documentElement.clientHeight;
				
				// przesuniecie miniatury wzgledem elementu uruchamiajacego
				var xOffset,yOffset = 70;
				
				// pozycja elementu uruchamiajacego wzgledem dokumentu
				var off = $(this).offset();
				
				// odleglosc elementu uruchamiajacego od dolnej krawedzi
				var space = scroll + winHeig - off.top;
				
				// przesuniecie minitaury w zaleznosci od wolnego miejsca
				// mozliwe 3 pozycje (ponizej, wycentrowane i powyzej)
				if(space > thumbHeight) xOffset = 0;//parseInt(linkHeight/2);
				else if(space < parseInt(thumbHeight/2)) xOffset = thumbHeight;
				else xOffset = parseInt(thumbHeight/2);
				
				this.t = this.title;
				this.title = "";
				$("body").append("<p id='screenshot' style='" + thumbStyle + "'><img src='"+ this.rel +"' /></p>");								 
				$("#screenshot")
					.css("top",(off.top - xOffset) + "px")
					.css("left",(off.left + yOffset) + "px")
					.fadeIn("fast");
			},
			function(){
				this.title = this.t;	
				$("#screenshot").remove();
		    });			
	
	
	
	$(".digits_only").keypress(function(event) {
		
		if (event.keyCode == 8)
			return true;
		
		if (event.keyCode == 46) {	 	
	 		return true;	 		
	 	}
		
		if (event.keyCode == 9) {
			return true;
		}
		
		var c = String.fromCharCode(event.charCode);
		if (("0123456789".indexOf(c) == -1)) {
			return false;
		};
		
	})
	
	$("#licence_type").change(function(event){
		var selected = $("#licence_type option:selected");
	/*	
		if(selected.val() != 6)
			$("#licence_name_row").addClass("hidden_row")
		else
			$("#licence_name_row").deleteClass("hidden_row")
	*/
		if(selected.val() != 6) 
		{
			$("#licence_name_row").hide();
		}
		else
			$("#licence_name_row").show();
	
	})
	
	
	$("#datownik1").keyup(function (event) {

		var t0 = $("#start_date").html();
		
		var startDate = Date.parse(t0);
		if (startDate < Date.today()) {
			startDate = Date.today();
		}
		
		if (isNaN(this.value))
			value = 0;
		else
			value = this.value;
		
		var tmp = startDate.addDays(value).toString('yyyy-MM-dd');				 	 	
		$('#end_date').val(tmp);
		
	})
	
	
	
	
	
    $('a.download').click(function(){
    	var id;
    	var count;
    	var maxDownloads;
    	if ($('#maxDownloads').val() != '' && isInteger($('#maxDownloads').val())){
    		maxDownloads = parseInt($('#maxDownloads').val());
    	}else{
    		maxDownloads = 0;
    	}    	
    	id = $(this).attr('id');
    	if ($('#download_count_'+id).html() != '' && isInteger($('#download_count_'+id).html())){
    		count = parseInt($('#download_count_'+id).html());
    	}else{
    		count = 0;
    	}
    	if (count < maxDownloads)
    		count++;
    	$('#download_count_'+id).html(count);
    });	
    
    function removeDistinction(id){
        
		if(id >= 0){
			$.ajax({
            type: 'POST',       
            url: url_variable + 'moje-biteo/oferty/dodaj-oferte/usun-wyroznienie/',
            dataType: 'json',
            data: {
                id_distinction: id
            },
            success: function(data){       
                if (data[0] == 'error') {
                    return $('.bottomErr').text(data[1]);
                } else {
                    $('#distinction_list tbody').children('tr').remove();
                    //$('#distinction_summary_list tbody').children('tr').remove();
                    for(var i=0; i < data[1].length; i++) {
                        $('#distinction_list').append(createDistinctionRow(i, data[1][i]));
                        $('#distinction_list').append(createErrorRow(i));
                        $('#start_date_'+i).bind('blur',function(){
                            createNewRowsNew(i);    
                        });
                        
                        $('#end_date_'+i).bind('blur',function(){
                            createNewRowsNew(i);    
                        });  
    					$('.editDates').click(function(){
    						editDatesNew(this.title);
    					});                       
                    }
                    if (data[1].length == 0){
                		 $('#distinction_list thead').hide();
                    }
                    $('#dist_summary').html(createDisctinctionSummary());
					$('.removeDistinction').click(function(){
						removeDistinction(this.title);
					});
                }
            }
        }); 
		}
	}
    
    function removeDistinctionEdt(id){
        
		if(id >= 0){
			$.ajax({
            type: 'POST',       
            url: url_variable + 'moje-biteo/oferta/usun-wyroznienie/',
            dataType: 'json',
            data: {
                id_distinction: id
            },
            success: function(data){       
                if (data[0] == 'error') {
                    return $('.bottomErr').text(data[1]);
                } else {
                    $('#distinction_list_edit tbody').children('tr').remove();
                    for(var i=0; i < data[1].length; i++) {
                        if (data[1][i]['delete'] != 1)
                          $('#distinction_list_edit').append(createDistinctionRowEdt(i, data[1][i]));
                          $('#distinction_list_edit').append(createErrorRow(i));
                    }
                    if (data[1].length == 0){
               		 $('#distinction_list_edit thead').hide();
                    }             
                    $('#dist_summary').html(createDisctinctionSummaryEdt());
					$('.removeDistinction').click(function(){
						removeDistinctionEdt(this.title);
					});
					$('.editDates').click(function(){
						editDates(this.title);
					});       
					$('.editEndDate').click(function(){
						editEndDate(this.title);
					});                                       
                }
            }
        }); 
		}
	}	
    
    function createNewRows(i){
                    $.ajax({
                        type: 'POST',       
                        url: url_variable + 'moje-biteo/oferta/przelicz-wyroznienia/',
                        dataType: 'json',
                        data: {
                            form : $('#distForm').serialize()
                        },
                        success: function(data){       
				            if (data[0] == 'error') {
                                return $('.bottomErr').text(dist[1]);
                            } else {
                              //  $('#distinction_list_edit tbody').children('tr').remove();
                                for (var j = 0; j < data[1].length; j++) {
                                    //$('#distinction_list_edit').append(createDistinctionRowEdt(j, data[1][j]));
                                    if (i == j){
                                        /*$('#start_date_' + i).html('');
                                        $('#end_date_' + i).html('');
                                        $('#start_date_' + i).html('<input id="start_date_' + i + '" class="date" type="text" name="distinction_offer_start_date_' + i + '" checked="checked" value="' + data[1][j].start_date + '" class="distinction_offer_start_date" readonly="readonly" onfocus="Calendar(\'DatePicker_distinction_offer_start_date_' + i + '\',this)"  /><div class="clndr" id="DatePicker_distinction_offer_start_date_' + i + '"> </div>');
                                        $('#end_date_' + i).html('<input id="end_date_' + i + '" class="date" type="text" name="distinction_offer_end_date_' + i + '" checked="checked" value="' + data[1][j].end_date + '" class="distinction_offer_end_date" readonly="readonly" onfocus="Calendar(\'DatePicker_distinction_offer_end_date_' + i + '\',this)" /><div class="clndr" id="DatePicker_distinction_offer_end_date_' + i + '"> </div>');     
                                        $('#start_date_' + i).children('input').blur(function(){
                                          createNewRows(i);
                  
               	                        });  
                                        $('#end_date_' + i).children('input').blur(function(){
                                           createNewRows(i);
                  
               	                        });*/
                                    	$('#start_date_'+i).val(data[1][i].start_date);
                                    	$('#end_date_'+i).val(data[1][i].end_date);
                                    	$('#distinction_offer_cost_'+i).html(parseFloat(data[1][i].cost).toFixed(2));
                                                                                                                  
                                    }
                                     //$('#distinction_list_edit').append(createErrorRow(j));
                                }
                                $('#dist_summary').html(createDisctinctionSummaryEdt());
                                $('.removeDistinction').click(function(){
                                    removeDistinctionEdt(this.title);
                                });
					            $('.editDates').click(function(){
					            	editDates(this.title);
				            	});       
					            $('.editEndDate').click(function(){
					            	editEndDate(this.title);
					            });       
                            }
                        }
                    });           
    }
    
    function createNewRowsNew(i){
                    $.ajax({
                        type: 'POST',       
                        url: url_variable + 'moje-biteo/oferta/przelicz-nowe-wyroznienia/',
                        dataType: 'json',
                        data: {
                            form : $('#addForm').serialize()
                        },
                        success: function(data){       
				            if (data[0] == 'error') {
                                return $('.bottomErr').text(dist[1]);
                            } else {
                                //$('#distinction_list tbody').children('tr').remove();
                                for (var j = 0; j < data[1].length; j++) {
                                    //$('#distinction_list').append(createDistinctionRow(j, data[1][j]));
                                    //$('#distinction_list').append(createErrorRow(j));
                                    if (i == j){
                                       /* $('#start_date_' + i).html('');
                                        $('#end_date_' + i).html('');
                                        $('#start_date_' + i).html('<input id="start_date_' + i + '" class="date" type="text" name="distinction_offer_start_date_' + i + '" checked="checked" value="' + data[1][j].start_date + '" class="distinction_offer_start_date" readonly="readonly" onfocus="Calendar(\'DatePicker_distinction_offer_start_date_' + i + '\',this)"  /><div class="clndr" id="DatePicker_distinction_offer_start_date_' + i + '"> </div>');
                                        $('#end_date_' + i).html('<input id="end_date_' + i + '" class="date" type="text" name="distinction_offer_end_date_' + i + '" checked="checked" value="' + data[1][j].end_date + '" class="distinction_offer_end_date" readonly="readonly" onfocus="Calendar(\'DatePicker_distinction_offer_end_date_' + i + '\',this)" /><div class="clndr" id="DatePicker_distinction_offer_end_date_' + i + '"> </div>');     
                                        $('#start_date_' + i).children('input').blur(function(){
                                          createNewRowsNew(i);
                  
               	                        });  
                                        $('#end_date_' + i).children('input').blur(function(){
                                           createNewRowsNew(i);
                  
               	                        });    */
                                    	$('#start_date_'+i).val(data[1][i].start_date);
                                    	$('#end_date_'+i).val(data[1][i].end_date);
                                    	$('#distinction_offer_cost_'+i).html(parseFloat(data[1][i].cost).toFixed(2));
                                                                                                                  
                                    }                                 
                                    /*$('#start_date_'+j).bind('blur',function(){
                                        createNewRowsNew(j);    
                                    });
                        
                                    $('#end_date_'+j).bind('blur',function(){
                                        createNewRowsNew(j);    
                                    });   */ 
                                }
                                $('#dist_summary').html(createDisctinctionSummary());
                                $('.removeDistinction').click(function(){
                                    removeDistinction(this.title);
                                });  
                            }
                        }
                    });           
    }    
       
    
    function createNewRow(i){
        $.ajax({
            type: 'POST',       
            url: url_variable + 'moje-biteo/oferta/przelicz-wyroznienia/',
            dataType: 'json',
            data: {
                form : $('#distForm').serialize()
            },
            success: function(data){       
	            if (data[0] == 'error') {
                    return $('.bottomErr').text(dist[1]);
                } else {
                   // $('#distinction_list_edit tbody').children('tr').remove();
                    for (var j = 0; j < data[1].length; j++) {
                        //$('#distinction_list_edit').append(createDistinctionRowEdt(j, data[1][j]));
                        if (i == j){
                           /* $('#end_date_' + i).html('');
                            $('#end_date_' + i).html('<input id="end_date_' + i + '" class="date" type="text" name="distinction_offer_end_date_' + i + '" checked="checked" value="' + data[1][j].end_date + '" class="distinction_offer_end_date" readonly="readonly" onfocus="Calendar(\'DatePicker_distinction_offer_end_date_' + i + '\',this)" /><div class="clndr" id="DatePicker_distinction_offer_end_date_' + i + '"> </div>');        
                            $('#end_date_' + i).children('input').blur(function(){
                                 createNewRow(i);
                            });  */
                        	$('#end_date_'+i).val(data[1][i].end_date);
                        	$('#distinction_offer_cost_'+i).html(parseFloat(data[1][i].cost).toFixed(2));                        	
                        }
                         //$('#distinction_list_edit').append(createErrorRow(j));
                    }
                    $('#dist_summary').html(createDisctinctionSummaryEdt());
                    $('.removeDistinction').click(function(){
                        removeDistinctionEdt(this.title);
                    });
		            $('.editDates').click(function(){
		            	editDates(this.title);
	            	});       
		            $('.editEndDate').click(function(){
		            	editEndDate(this.title);
		            });       
                }
            }
        });           
}        
    
    function editDates(i){
		if(i >= 0){
            var start_date_obj = $('#start_date_'+i);
            var end_date_obj = $('#end_date_'+i);
            if (typeof(start_date_obj.children('input').val()) == 'undefined' && typeof(end_date_obj.children('input').val()) == 'undefined') {
                var start_date = start_date_obj.html();
                var end_date = end_date_obj.html();
                $('#start_date_' + i).html('');
                $('#end_date_' + i).html('');
                $('#start_date_' + i).html('<input id="start_date_' + i + '" class="date" type="text" name="distinction_offer_start_date_' + i + '" checked="checked" value="' + start_date + '" class="distinction_offer_start_date"  readonly="readonly" onfocus="Calendar(\'DatePicker_distinction_offer_start_date_' + i + '\',this)" /><div class="clndr" id="DatePicker_distinction_offer_start_date_' + i + '"> </div>');
                $('#end_date_' + i).html('<input id="end_date_' + i + '" class="date" type="text" name="distinction_offer_end_date_' + i + '" checked="checked" value="' + end_date + '" class="distinction_offer_end_date" readonly="readonly" onfocus="Calendar(\'DatePicker_distinction_offer_end_date_' + i + '\',this)"  /><div class="clndr" id="DatePicker_distinction_offer_end_date_' + i + '"> </div>');
                $('#start_date_' + i).children('input').blur(function(){
                  createNewRows(i);
                  
                });
                $('#end_date_' + i).children('input').blur(function(){
                  createNewRows(i);
                  
                });                
            }
        }
	}	    
    
    function editEndDate(i){
        
		if(i >= 0){
            var end_date_obj = $('#end_date_'+i);
            if (typeof(end_date_obj.children('input').val()) == 'undefined') {
                var end_date = end_date_obj.html();
                 $('#end_date_' + i).html('');
                 
                 $('#end_date_' + i).html('');
                $('#end_date_' + i).append('<input  id="end_date_' + i + '" class="date" type="text" name="distinction_offer_end_date_' + i + '" checked="checked" value="' + end_date + '" class="distinction_offer_end_date" readonly="readonly" onfocus="Calendar(\'DatePicker_distinction_offer_end_date_' + i + '\',this)" /><div class="clndr DatePickerDistinctionOffer" id="DatePicker_distinction_offer_end_date_' + i + '"> </div>');
                            
               // var tmpval =  $('#end_date_' + i).children('input').
               
                $('#end_date_' + i).children('input').blur(function(){
                   createNewRow(i);
                });
                /*$('#end_date_' + i).children('input').click(function(){
                  createNewRow(i);
                  
                }); */    
            }
        }
	}	
    
    function editDatesNew(i){
		if(i >= 0){
            var start_date_obj = $('#start_date_'+i);
            var end_date_obj = $('#end_date_'+i);
            if (typeof(start_date_obj.children('input').val()) == 'undefined' && typeof(end_date_obj.children('input').val()) == 'undefined') {
                var start_date = start_date_obj.html();
                var end_date = end_date_obj.html();
                $('#start_date_' + i).html('');
                $('#end_date_' + i).html('');
                $('#start_date_' + i).html('<input id="start_date_' + i + '" class="date" type="text" name="distinction_offer_start_date_' + i + '" checked="checked" value="' + start_date + '" class="distinction_offer_start_date"  readonly="readonly" onfocus="Calendar(\'DatePicker_distinction_offer_start_date_' + i + '\',this)" /><div class="clndr" id="DatePicker_distinction_offer_start_date_' + i + '"> </div>');
                $('#end_date_' + i).html('<input id="end_date_' + i + '" class="date" type="text" name="distinction_offer_end_date_' + i + '" checked="checked" value="' + end_date + '" class="distinction_offer_end_date" readonly="readonly" onfocus="Calendar(\'DatePicker_distinction_offer_end_date_' + i + '\',this)"  /><div class="clndr" id="DatePicker_distinction_offer_end_date_' + i + '"> </div>');
                $('#start_date_' + i).children('input').blur(function(){
                  createNewRowsNew(i);
                  
                });
                $('#end_date_' + i).children('input').blur(function(){
                  createNewRowsNew(i);
                  
                });                
            }
        }
	}	            


	
	$('.distincition_btn').children('a').click(function(){

        var id_distinction = $('#distinction').val();
        var start_date = $('#distinction_offer_start_date').val();
        var end_date = $('#distinction_offer_end_date').val();
        var tDate = new Date();
        var tYear = tDate.getFullYear();
        var tMonth = tDate.getMonth()+1;
        if (tMonth < 10) {
            tMonth = '0'+tMonth;
        }
        var tDay = tDate.getDate();
        if (tDay < 10) {
            tDay = '0'+tDay;
        }
        var today_date = tYear+'-'+tMonth+'-'+tDay;
        var date_validator = /^([0-9]{1,4})\-([0-9]{1,2})\-([0-9]{1,2})$/;
        
        //validate section
        if (start_date == '') {
			
            return $('.bottomErr').text('Musisz podać datę rozpoczęcia wyróżnienia');
        } else if (start_date.replace('-','') < today_date.replace('-','')) {
			
            return $('.bottomErr').text('Data rozpoczęcia wyróżnienia nie może być ustawiona wstecz');
        } else if (end_date == '') {
			
            return $('.bottomErr').text('Musisz podać datę zakończenia wyróżnienia');
        }
        if (isDate(start_date) == false) {
		
            return $('.bottomErr').text('Nieprawidłowy format daty rozpoczęcia wyróżnienia');
        } else if (isDate(end_date) == false) {
			
            return $('.bottomErr').text('Nieprawidłowy format daty zakończenia wyróżnienia');
        } else if (start_date.replace('-','') > end_date.replace('-','')) {
			
            return $('.bottomErr').text('Data zakończenia wyróżnienia nie może być wcześniejsza niż data rozpoczęcia');
        } else {
			
            $('.bottomErr').text('');
        }
        // end validate
        
        $.ajax({
            type: 'POST',       
            url: url_variable + 'moje-biteo/oferty/dodaj-oferte/dodaj-wyroznienie/',
            dataType: 'json',
            data: {
                id_distinction: id_distinction,
                start_date: start_date,
                end_date: end_date
            },
            success: function(dist){       
				if (dist[0] == 'error') {
                    return $('.bottomErr').text(dist[1]);
                } else {
					$('#distinction_list tbody').children('tr').remove();
                    //$('#distinction_summary_list tbody').children('tr').remove();
                    for(var i=0; i < dist[1].length; i++) {
                        $('#distinction_list').append(createDistinctionRow(i, dist[1][i]));
                        $('#distinction_list').append(createErrorRow(i));
                        $('#start_date_'+i).bind('blur',function(){
                            createNewRowsNew(i);    
                        });
                        
                        $('#end_date_'+i).bind('blur',function(){
                            createNewRowsNew(i);    
                        });                          
                    }
                    $('#dist_summary').html(createDisctinctionSummary());
					$('.removeDistinction').click(function(){
						removeDistinction(this.title);
					});
					$('.editDates').click(function(){
						editDatesNew(this.title);
					});       					
					// clean inputs
					$('#distinction_offer_start_date').val('');
					$('#distinction_offer_end_date').val('');
                }
            }
        }); 
    });
    
    if (document.getElementById('distinction_list')) {
        $.ajax({
            type: 'POST',
            url: url_variable + 'moje-biteo/oferty/dodaj-oferte/lista-wyroznien/',
            dataType: 'json',
            data: {},
            success: function(data){
                if (data[1].length) {
                    $('#distinction_list tbody').children('tr').remove();
                   // $('#distinction_summary tbody').children('tr').remove();
                    for (var i = 0; i < data[1].length; i++) {
                        $('#distinction_list').append(createDistinctionRow(i, data[1][i]));
                        $('#distinction_list').append(createErrorRow(i));
                        //$('#distinction_summary_list').append(createDistinctionSummaryRow(i, data[1][i]));
                        
                        $('#start_date_'+i).bind('blur',function(){
                            createNewRowsNew(i);    
                        });
                        
                        $('#end_date_'+i).bind('blur',function(){
                            createNewRowsNew(i);    
                        });                        
                        
                    }
                    $('#dist_summary').html(createDisctinctionSummary());
                    $('.removeDistinction').click(function(){
                        removeDistinction(this.title);
                    });
					$('.editDates').click(function(){
						editDatesNew(this.title);
					});                            
                }
            }
        });
    }
    
    if (document.getElementById('distinction_list_edit')) {

        $.ajax({
            type: 'POST',
            url: url_variable + 'moje-biteo/oferta/lista-wyroznien/',
            dataType: 'json',
            data: {
                'offer_id': $('#offer_id').val(),
                'offer_copy':$('#offer_copy').val()
            },
            success: function(data){
                if (data[1].length) {
                    $('#distinction_list tbody').children('tr').remove();
                    for (var i = 0; i < data[1].length; i++) {
                        $('#distinction_list_edit').append(createDistinctionRowEdt(i, data[1][i]));
                         $('#distinction_list_edit').append(createErrorRow(i));
                    }
                    $('#dist_summary').html(createDisctinctionSummaryEdt());
                    $('.removeDistinction').click(function(){
                        removeDistinctionEdt(this.title);
                    });
					$('.editDates').click(function(){
						editDates(this.title);
					});       
					$('.editEndDate').click(function(){
						editEndDate(this.title);
					});                                       
                }
            }
        });
    }
    
	$('.distincition_edt_btn').children('a').click(function(){

        var id_distinction = $('#distinction').val();
        var start_date = $('#distinction_offer_start_date').val();
        var end_date = $('#distinction_offer_end_date').val();
        var dist_offer_id = $('#dist_offer_id').val();
        var tDate = new Date();
        var tYear = tDate.getFullYear();
        var tMonth = tDate.getMonth()+1;
        if (tMonth < 10) {
            tMonth = '0'+tMonth;
        }
        var tDay = tDate.getDate();
        if (tDay < 10) {
            tDay = '0'+tDay;
        }
        var today_date = tYear+'-'+tMonth+'-'+tDay;
        var date_validator = /^([0-9]{1,4})\-([0-9]{1,2})\-([0-9]{1,2})$/;
        
        //validate section
        if (start_date == '') {
			
            return $('.bottomErr').text('Musisz podać datę rozpoczęcia wyróżnienia');
        } else if (start_date.replace('-','') < today_date.replace('-','')) {
			
            return $('.bottomErr').text('Data rozpoczęcia wyróżnienia nie może być ustawiona wstecz');
        } else if (end_date == '') {
			
            return $('.bottomErr').text('Musisz podać datę zakończenia wyróżnienia');
        }
        if (isDate(start_date) == false) {
			
            return $('.bottomErr').text('Nieprawidłowy format daty rozpoczęcia wyróżnienia');
        } else if (isDate(end_date) == false) {
			
            return $('.bottomErr').text('Nieprawidłowy format daty zakończenia wyróżnienia');
        } else if (start_date.replace('-','') > end_date.replace('-','')) {
			
            return $('.bottomErr').text('Data zakończenia wyróżnienia nie może być wcześniejsza niż data rozpoczęcia');
        } else {
			
            $('.bottomErr').text('');
        }
        // end validate
        $.ajax({
            type: 'POST',       
            url: url_variable + 'moje-biteo/oferta/dodaj-wyroznienie-edycja/',
            dataType: 'json',
            data: {
                id_distinction: id_distinction,
                start_date: start_date,
                end_date: end_date,
                dist_offer_id: dist_offer_id
            },
            success: function(dist){     
				if (dist[0] == 'error') {
                    return $('.bottomErr').text(dist[1]);
                } else {
					$('#distinction_list_edit tbody').children('tr').remove();
                    //$('#distinction_summary_list tbody').children('tr').remove();
                    for(var i=0; i < dist[1].length; i++) {
                        $('#distinction_list_edit').append(createDistinctionRowEdt(i, dist[1][i]));
                         $('#distinction_list_edit').append(createErrorRow(i));
                    }
                    $('#dist_summary').html(createDisctinctionSummaryEdt());
					$('.removeDistinction').click(function(){
						removeDistinctionEdt(this.title);
					});
					$('.editDates').click(function(){
						editDates(this.title);
					});       
					$('.editEndDate').click(function(){
						editEndDate(this.title);
					});                                     
					
					// clean inputs
					$('#distinction_offer_start_date').val('');
					$('#distinction_offer_end_date').val('');
                }
            }
        }); 
    });
    
     
    
    $('#distSave').click(function () {
      var start_date;  
      var end_date;
      var start_date2;  
      var end_date2;
      var id_distinction;
      var id_distinction2;
      var start_date_editable;
      var end_date_editable;
        var tDate = new Date();
        var tYear = tDate.getFullYear();
        var tMonth = tDate.getMonth()+1;
        if (tMonth < 10) {
            tMonth = '0'+tMonth;
        }
        var tDay = tDate.getDate();
        if (tDay < 10) {
            tDay = '0'+tDay;
        }
        var today_date = tYear+'-'+tMonth+'-'+tDay;
        var date_validator = /^([0-9]{1,4})\-([0-9]{1,2})\-([0-9]{1,2})$/;
        var submit = true;
        var index = 0;
      $('table#distinction_list_edit tbody tr.dataRow').each(function (){
          var i = 0;
          var start_date_obj = $(this).children('td').next('td').next('td');

          if (typeof(start_date_obj.children('div.start_date').children('input').val()) != 'undefined'){
              start_date = start_date_obj.children('div.start_date').children('input').val();
              start_date_editable = true;         
          }else if (start_date_obj.children('div.start_date').html() != ''){
              start_date = start_date_obj.children('div.start_date').html();
              start_date_editable = false; 
          }else{
              start_date = '';
              start_date_editable = false; 
          }

          
          var end_date_obj = $(this).children('td').next('td').next('td').next('td');
          if (typeof(end_date_obj.children('div.end_date').children('input').val()) != 'undefined'){
              end_date = end_date_obj.children('div.end_date').children('input').val();
              end_date_editable = true;
          }else if (end_date_obj.children('div.end_date').html() != ''){
               end_date = end_date_obj.children('div.end_date').html();
               end_date_editable = false;
          }else{
              end_date = ''; 
              end_date_editable = false;
          }


          id_distinction = $(this).children('td').children('input.id_distinction').val();        
          //alert(id_distinction);
          if (start_date == '') {
              submit = false;
            $('td.error_'+index).text('Musisz podać datę rozpoczęcia wyróżnienia');
            $('tr.hiddenErrorBox_'+index).show();
          } else if ((start_date.replace('-','') < today_date.replace('-','')) && start_date_editable) {
              submit = false;
               $('td.error_'+index).text('Data rozpoczęcia wyróżnienia nie może być ustawiona wstecz');
               $('tr.hiddenErrorBox_'+index).show();
          } else if ((end_date.replace('-','') < today_date.replace('-','')) && end_date_editable) {
              submit = false;
               $('td.error_'+index).text('Data zakończenia wyróżnienia nie może być ustawiona wstecz');
               $('tr.hiddenErrorBox_'+index).show();
          } else if (end_date == '') {
              submit = false;
              $('td.error_'+index).text('Musisz podać datę zakończenia wyróżnienia');
              $('tr.hiddenErrorBox_'+index).show();
          }
          if (isDate(start_date) == false) {
              submit = false;
              $('td.error_'+index).text('Nieprawidłowy format daty rozpoczęcia wyróżnienia');
              $('tr.hiddenErrorBox_'+index).show();
          } else if ( isDate(end_date) == false) {
              submit = false;
              $('td.error_'+index).text('Nieprawidłowy format daty zakończenia wyróżnienia');
              $('tr.hiddenErrorBox_'+index).show();
          } else if (start_date.replace('-','') > end_date.replace('-','')) {
              submit = false;
             $('td.error_'+index).text('Data zakończenia wyróżnienia nie może być wcześniejsza niż data rozpoczęcia');
             $('tr.hiddenErrorBox_'+index).show();
          } else {

            $('table#distinction_list_edit tbody tr.dataRow').each(function (){
            if (index != i) {
              var start_date2_obj = $(this).children('td').next('td').next('td');
              if (typeof(start_date2_obj.children('div').children('input').val()) != 'undefined'){
                  start_date2 = start_date2_obj.children('div').children('input').val();     
              }else if (start_date2_obj.children('div').html() != ''){
                  start_date2 = start_date2_obj.children('div').html();
              }else{
                  start_date = '';
              }
          
          
              var end_date2_obj = $(this).children('td').next('td').next('td').next('td');
              if (typeof(end_date2_obj.children('div').children('input').val()) != 'undefined'){
                  end_date2 = end_date2_obj.children('div').children('input').val();
              }else if (end_date2_obj.children('div').html() != ''){
                   end_date2 = end_date2_obj.children('div').html();
              }else{
                  end_date2 = ''; 
              }
                    
                
               // start_date2 = $(this).children('td').next('td').children('div').children('input').val();
               // end_date2 = $(this).children('td').next('td').children('div').next('div').children('input').val();
                id_distinction2 = $(this).children('td').children('input.id_distinction').val(); 

                if ((id_distinction == id_distinction2)) {
                    if (!((start_date.replace('-', '') < start_date2.replace('-', '')) &&
                    (end_date.replace('-', '') < start_date2.replace('-', '')) ||
                    (start_date.replace('-', '') > end_date2.replace('-', '')) &&
                    (end_date.replace('-', '') > end_date2.replace('-', '')))) {
                        submit = false;
                        $('td.error_'+index).text('Podany okres wyróżnienia pokrywa się już z obecnie ustawionym');
                        $('tr.hiddenErrorBox_'+index).show();
                    }
                }
            }
              i++;
          });    
          
          if (submit) {
              $('td.error_'+index).text(''); 
              $('tr.hiddenErrorBox_'+index).hide(); 
          }
              //$(this).children('td').next('td').children('div').next('div').next('div').text('');
              
          }



          index++;   
      });          
     if (submit) {    
          $('#distForm').submit();
      }
    });
    
    
    $('#addButton').click(function () {
      var start_date;  
      var end_date;
      var start_date2;  
      var end_date2;
      var id_distinction;
      var id_distinction2;
      var start_date_editable;
        var tDate = new Date();
        var tYear = tDate.getFullYear();
        var tMonth = tDate.getMonth()+1;
        if (tMonth < 10) {
            tMonth = '0'+tMonth;
        }
        var tDay = tDate.getDate();
        if (tDay < 10) {
            tDay = '0'+tDay;
        }
        var today_date = tYear+'-'+tMonth+'-'+tDay;
        var date_validator = /^([0-9]{1,4})\-([0-9]{1,2})\-([0-9]{1,2})$/;
        var submit = true;
        var index = 0;

        $('table#distinction_list tbody tr.dataRow').each(function (){
            var i = 0;
            var start_date_obj = $(this).children('td').next('td').next('td');

            if (typeof(start_date_obj.children('div.start_date').children('input').val()) != 'undefined'){
                start_date = start_date_obj.children('div.start_date').children('input').val();
                start_date_editable = true;         
            }else if (start_date_obj.children('div.start_date').html() != ''){
                start_date = start_date_obj.children('div.start_date').html();
                start_date_editable = false; 
            }else{
                start_date = '';
                start_date_editable = false; 
            }

            
            var end_date_obj = $(this).children('td').next('td').next('td').next('td');
            if (typeof(end_date_obj.children('div.end_date').children('input').val()) != 'undefined'){
                end_date = end_date_obj.children('div.end_date').children('input').val();
                end_date_editable = true;
            }else if (end_date_obj.children('div.end_date').html() != ''){
                 end_date = end_date_obj.children('div.end_date').html();
                 end_date_editable = false;
            }else{
                end_date = ''; 
                end_date_editable = false;
            }

            id_distinction = $(this).children('td').children('input.id_distinction').val();        
            //alert(id_distinction);
            if (start_date == '') {
                submit = false;
              $('td.error_'+index).text('Musisz podać datę rozpoczęcia wyróżnienia');
              $('tr.hiddenErrorBox_'+index).show();
            } else if ((start_date.replace('-','') < today_date.replace('-','')) && start_date_editable) {
                submit = false;
                 $('td.error_'+index).text('Data rozpoczęcia wyróżnienia nie może być ustawiona wstecz');
                 $('tr.hiddenErrorBox_'+index).show();
            } else if ((end_date.replace('-','') < today_date.replace('-','')) && end_date_editable) {
                submit = false;
                 $('td.error_'+index).text('Data zakończenia wyróżnienia nie może być ustawiona wstecz');
                 $('tr.hiddenErrorBox_'+index).show();
            } else if (end_date == '') {
                submit = false;
                $('td.error_'+index).text('Musisz podać datę zakończenia wyróżnienia');
                $('tr.hiddenErrorBox_'+index).show();
            }
            if (isDate(start_date) == false) {
                submit = false;
                $('td.error_'+index).text('Nieprawidłowy format daty rozpoczęcia wyróżnienia');
                $('tr.hiddenErrorBox_'+index).show();
            } else if ( isDate(end_date) == false) {
                submit = false;
                $('td.error_'+index).text('Nieprawidłowy format daty zakończenia wyróżnienia');
                $('tr.hiddenErrorBox_'+index).show();
            } else if (start_date.replace('-','') > end_date.replace('-','')) {
                submit = false;
               $('td.error_'+index).text('Data zakończenia wyróżnienia nie może być wcześniejsza niż data rozpoczęcia');
               $('tr.hiddenErrorBox_'+index).show();
            } else {

              $('table#distinction_list tbody tr.dataRow').each(function (){
              if (index != i) {
                var start_date2_obj = $(this).children('td').next('td').next('td');
                if (typeof(start_date2_obj.children('div').children('input').val()) != 'undefined'){
                    start_date2 = start_date2_obj.children('div').children('input').val();     
                }else if (start_date2_obj.children('div').html() != ''){
                    start_date2 = start_date2_obj.children('div').html();
                }else{
                    start_date = '';
                }
            
            
                var end_date2_obj = $(this).children('td').next('td').next('td').next('td');
                if (typeof(end_date2_obj.children('div').children('input').val()) != 'undefined'){
                    end_date2 = end_date2_obj.children('div').children('input').val();
                }else if (end_date2_obj.children('div').html() != ''){
                     end_date2 = end_date2_obj.children('div').html();
                }else{
                    end_date2 = ''; 
                }
                      
                  
                 // start_date2 = $(this).children('td').next('td').children('div').children('input').val();
                 // end_date2 = $(this).children('td').next('td').children('div').next('div').children('input').val();
                  id_distinction2 = $(this).children('td').children('input.id_distinction').val(); 

                  if ((id_distinction == id_distinction2)) {
                      if (!((start_date.replace('-', '') < start_date2.replace('-', '')) &&
                      (end_date.replace('-', '') < start_date2.replace('-', '')) ||
                      (start_date.replace('-', '') > end_date2.replace('-', '')) &&
                      (end_date.replace('-', '') > end_date2.replace('-', '')))) {
                          submit = false;
                          $('td.error_'+index).text('Podany okres wyróżnienia pokrywa się już z obecnie ustawionym');
                          $('tr.hiddenErrorBox_'+index).show();
                      }
                  }
              }
                i++;
            });    
            
            if (submit) {
                $('td.error_'+index).text(''); 
                $('td.error_'+index).hide();
            }
                //$(this).children('td').next('td').children('div').next('div').next('div').text('');
                
            }



            index++;   
        });            
      if (submit) {
       /* var inputy = new Array();
        var input = new Array(); 
       
        $('table#distinction_list tbody tr').each(function (){
          
          input['start_date'] = $(this).children('td').next('td').children('div').children('input').val();
          input['end_date'] = $(this).children('td').next('td').children('div').next('div').children('input').val();
          inputy.push(input);
          
        });  */
            //var cos = $('#addForm').serialize();
           // alert(cos);
        //  var_dump(inputy);
          /*$.ajax({
            type: 'POST',       
            url: url_variable + 'moje-biteo/oferta/edycja-wyroznienia/',
            dataType: 'json',
            data: cos
                     
         }); */
          $('#addForm').submit();
      }
    });        
    
	
	/* POUPS - info clouds */
	
	$('div.infoIco').hover(function(){
		
		var off = $(this).parent('div.infoRel').offset();
		var description = $(this).children('span.hiddenInfo').html();
		var spanInside = $("<span></span>").html(description);
		var defaultHeight='auto';
		$('div.mainInfoHidden2').append(spanInside);
		
		if (description.length<70){defaultHeight='60px'}
				
		if ($(this).hasClass('wideLabel')) {
			$('div.mainInfoHidden2').attr({
				"style": "top:" + (off.top - 28) + "px;left:" + (off.left + 50) + "px; position:absolute; display:block; 	width:150px; height:"+defaultHeight+";"
			});
		}
		else if ($(this).hasClass('wideCheckLabel')) {
			$('div.mainInfoHidden2').attr({
				"style": "top:" + (off.top - 28) + "px;left:" + (off.left + 90) + "px; position:absolute; display:block; 	width:150px; height:"+defaultHeight+";"
			});
		}
		else {
			$('div.mainInfoHidden2').attr({
				"style": "top:" + (off.top - 28) + "px;left:" + (off.left - 35) + "px; position:absolute; display:block; 	width:150px; height:"+defaultHeight+";"
			});
		}
		
	},function(){
		$('div.mainInfoHidden2').css('display','none');
		$('div.mainInfoHidden2').children('span').html('');
		//$('div.mainInfoHidden2').remove();
	});		
	
	/* Piotr Baldych, bug = 101, licencje */
	
	$('div.infoIcoLic').hover(function(){
		
		var off = $(this).parent('div.infoRel').offset();
		var lic_id = $("#licence_type option:selected").val();
		var description = $(this).children('span.hiddenInfo-' + lic_id).html();
		var spanInside = $("<span></span>").html(description);
		var defaultHeight='auto';
		$('div.mainInfoHidden2').append(spanInside);
		
		if (description.length<70){defaultHeight='60px'}
				
		if ($(this).hasClass('wideLabel')) {
			$('div.mainInfoHidden2').attr({
				"style": "top:" + (off.top - 28) + "px;left:" + (off.left + 50) + "px; position:absolute; display:block; 	width:150px; height:"+defaultHeight+";"
			});
		}
		else if ($(this).hasClass('wideCheckLabel')) {
			$('div.mainInfoHidden2').attr({
				"style": "top:" + (off.top - 28) + "px;left:" + (off.left + 90) + "px; position:absolute; display:block; 	width:150px; height:"+defaultHeight+";"
			});
		}
		else {
			$('div.mainInfoHidden2').attr({
				"style": "top:" + (off.top - 28) + "px;left:" + (off.left - 35) + "px; position:absolute; display:block; 	width:150px; height:"+defaultHeight+";"
			});
		}
		
	},function(){
		$('div.mainInfoHidden2').css('display','none');
		$('div.mainInfoHidden2').children('span').html('');
		//$('div.mainInfoHidden2').remove();
	});		
	
	$('.jsCheckPrice').click(function(){
		if ($(this).attr('checked') == false) {
			thisPriceJs = parseFloat($(this).attr('title'));
			jsNewPrice = jsNewPrice - thisPriceJs;
			
			var fixedNewPrice = Math.round(jsNewPrice * 100) / 100
			$('.newFilesJsPrice').html(fixedNewPrice.toFixed(2));
			
		}else{
			thisPriceJs = parseFloat($(this).attr('title'));
			jsNewPrice += thisPriceJs;
			
			var fixedNewPrice = Math.round(jsNewPrice * 100) / 100
			$('.newFilesJsPrice').html(fixedNewPrice.toFixed(2));
			
			//$('.newFilesJsPrice').html(jsNewPrice);	
		}
		

		if (jsNewPrice<=0) {
			$('.buttonBlue3').addClass('buttonBlue2Disabled');
			$('.buttonBlue3').attr('disabled', 'disabled');
			$('.buttonBlue3').attr('title', 'Wybierz minimum jeden plik');
		}
		
		if (jsNewPrice>0){
				$('.buttonBlue3').removeClass('buttonBlue2Disabled');
				$('.buttonBlue3').attr('disabled','');
				$('.buttonBlue3').attr('title','');
		}


	});
	
	/*
	 * Jaroslaw Selega
	 * bug = 53
	 */
	$('textarea.wysiwyg').each(function(){
		var oFCKeditor = new FCKeditor($(this).attr('id'),$(this).css('width'),$(this).css('height'),'Basic2');
		oFCKeditor.ReplaceTextarea();			
	});

	$('textarea.simple-wysiwyg').each(function(){
		var oFCKeditor = new FCKeditor($(this).attr('id'),$(this).css('width'),$(this).css('height'),'Basic3');
		oFCKeditor.ReplaceTextarea();			
	});
	
	
	$('.sortAjaxName').children('a').click(function(){
        $('span.checkedFilesPrice').html("0.00");
        offerPrice = 0;
		var sortDir = $('#sort_direct').val() == 'ASC' ? 'DESC' : 'ASC';
		$.ajax({
			type: 'POST',		
			url: url_variable + 'oferta/sortByName',
			dataType: 'json',
			data: {
				offer_id: $('#offer_id').val(),
				order_by: 'o_file_name',
				order: sortDir
			},
		  	success: function(data){       
				$('#sort_direct').val(sortDir);
				
				$('#offerFiles tbody').children('tr').not(':first-child').remove();
				
				
					
				for(var i=0; i < data.offer_files.length; i++) {


					$('#offerFiles ').append(createOfferRow(data.offer_files[i], i, data.offer_detail));;
					
					
				}		
				
				$('th input.check').click(function(){

                    if ($(this).attr('checked')) {
                        $(this).attr('checked', true);
                        $(this).parent('th').parent('tr').parent('tbody').children('tr').each(function(){
                            $(this).children('td.checkMe').children('input').attr('checked', true);
                        })
                    }
                    
                    if (!$(this).attr('checked')) {
                        $(this).attr('checked', false);
                        $(this).parent('th').parent('tr').parent('tbody').children('tr').each(function(){
                            $(this).children('td.checkMe').children('input').attr('checked', false);
                        })
                    }
                    
                });
				var offerActualPrice=parseFloat($('.offerDataPrice').attr('value'));
				$('.itemSubject').click(function(){
		
		if ($(this).attr('checked')==true)
		{
			
			val=$(this).val();
			tablica.push(val);
			
			valName=$(this).attr('title');			
			tablicaName.push(valName);
			offerPrice+=offerActualPrice;
			
			var offerPriceRound=Math.round(offerPrice*100)/100 
			
			if (offerPriceRound>0){
				$('.buttonBlue2').removeClass('buttonBlue2Disabled');
				$('.buttonBlue2').attr('disabled','');
				$('.buttonBlue2').attr('title','');

			}
			
			$('.checkedFilesPrice').html(offerPriceRound.toFixed(2));
			found = true;
			$('#offerFiles').find('tr td .itemSubject').each(function() {
				if ($(this).attr('checked') == false) {
					found = false;
				}
			});
			if (found) {
				$('table th input.checkIN').attr('checked', true);
			}
			//tablica[val]=val;
		}
		else
		{
			val=$(this).val();
			
			offerPrice=offerPrice-offerActualPrice;
			var offerPriceRound=Math.round(offerPrice*100)/100 
			
			$('.checkedFilesPrice').html(offerPriceRound.toFixed(2));

			if (offerPriceRound==0){
				$('.buttonBlue2').addClass('buttonBlue2Disabled');
				$('.buttonBlue2').attr('disabled','disabled');
				$('.buttonBlue2').attr('title','Wybierz minimum jeden plik');
			}
			
			for (key in tablica)
			{
				if (tablica[key]==val)
					tablica.splice(key,1);
			}
			
			valName=$(this).attr('title');
			for (key2 in tablicaName)
			{
				if (tablicaName[key2]==valName)
					tablicaName.splice(key2,1);
			}
			
			found = false;
			$('#offerFiles').find('tr td .itemSubject').each(function() {
				if ($(this).attr('checked') == false) {
					found = true;
				}
			});
			if (found) {
				$('table th input.checkIN').attr('checked', false);
			}
		}
	});
			}
		});	
	});
	
	$('.sortAjaxDate').children('a').click(function(){
        offerPrice = 0;
        $('span.checkedFilesPrice').html("0.00");
		var sortDir = $('#sort_direct').val() == 'ASC' ? 'DESC' : 'ASC';
		$.ajax({
			type: 'POST',		
			url: url_variable + 'oferta/sortByName',
			dataType: 'json',
			data: {
				offer_id: $('#offer_id').val(),
				order_by: 'o_modify_date',
				order: sortDir
			},
		  	success: function(data){       
				$('#sort_direct').val(sortDir);
				
				$('#offerFiles tbody').children('tr').not(':first-child').remove();
				
                 
				
				for(var i=0; i < data.offer_files.length; i++) {


					$('#offerFiles ').append(createOfferRow(data.offer_files[i], i, data.offer_detail));;
					
					
				}
                
       			$('th input.check').click(
                function(){

                    if ($(this).attr('checked')) {
                        $(this).attr('checked', true);
                        $(this).parent('th').parent('tr').parent('tbody').children('tr').each(function(){
                            $(this).children('td.checkMe').children('input').attr('checked', true);
                        })
                    }
                    
                    if (!$(this).attr('checked')) {
                        $(this).attr('checked', false);
                        $(this).parent('th').parent('tr').parent('tbody').children('tr').each(function(){
                            $(this).children('td.checkMe').children('input').attr('checked', false);
                        })
                    }
                    
                });
				var offerActualPrice=parseFloat($('.offerDataPrice').attr('value'));
				$('.itemSubject').click(function(){
		
		if ($(this).attr('checked')==true)
		{
			
			val=$(this).val();
			tablica.push(val);
			
			valName=$(this).attr('title');			
			tablicaName.push(valName);
			offerPrice+=offerActualPrice;
			
			var offerPriceRound=Math.round(offerPrice*100)/100 
			
			if (offerPriceRound>0){
				$('.buttonBlue2').removeClass('buttonBlue2Disabled');
				$('.buttonBlue2').attr('disabled','');
				$('.buttonBlue2').attr('title','');

			}
			
			$('.checkedFilesPrice').html(offerPriceRound.toFixed(2));
			found = true;
			$('#offerFiles').find('tr td .itemSubject').each(function() {
				if ($(this).attr('checked') == false) {
					found = false;
				}
			});
			if (found) {
				$('table th input.checkIN').attr('checked', true);
			}
			//tablica[val]=val;
		}
		else
		{
			val=$(this).val();
			
			offerPrice=offerPrice-offerActualPrice;
			var offerPriceRound=Math.round(offerPrice*100)/100 
			
			$('.checkedFilesPrice').html(offerPriceRound.toFixed(2));

			if (offerPriceRound==0){
				$('.buttonBlue2').addClass('buttonBlue2Disabled');
				$('.buttonBlue2').attr('disabled','disabled');
				$('.buttonBlue2').attr('title','Wybierz minimum jeden plik');
			}
			
			for (key in tablica)
			{
				if (tablica[key]==val)
					tablica.splice(key,1);
			}
			
			valName=$(this).attr('title');
			for (key2 in tablicaName)
			{
				if (tablicaName[key2]==valName)
					tablicaName.splice(key2,1);
			}
			
			found = false;
			$('#offerFiles').find('tr td .itemSubject').each(function() {
				if ($(this).attr('checked') == false) {
					found = true;
				}
			});
			if (found) {
				$('table th input.checkIN').attr('checked', false);
			}
		}
	});
			}
		});	
	});
	
	// Piotr Baldych, bug=115, kody aktywacyjne
	// event ukrywa i pokazuje odpowiednie elementy
	// na ekranie edycji pliku 
	// po kliknieciu w checkboxa "Przypisz do pliku kody aktywacji"
	$('#file_flag_codes').click(function(){
		
		if ($(this).attr('checked')) {
			$('#file_activation_code_row').hide();
			$('#codes-form').show();
		}
		else {
			$('#file_activation_code_row').show();
			$('#codes-form').hide();
		}
		
	});
	
	// -------------------------------------------------------------
	
	
	$('.alsoDemoFileCheck').click(function(){
	
		if ($(this).attr('checked')) {
			$('#id_file_demo').addClass('disableInputText');
			$('#id_file_demo').removeClass('clickDialogOneDemo');
			$('#id_file_demo').attr('disabled','disabled');
			$('#file_demo_boxLink').css('display','none');
		}
		else {
			$('#file_demo_boxLink').css('display','block');
			$('#id_file_demo').attr('disabled','');
			$('#id_file_demo').addClass('clickDialogOneDemo');
			$('#id_file_demo').removeClass('disableInputText');
		}
		
	});
	
	
	$('.alsoIconFileCheck').click(function(){
	
		if ($(this).attr('checked')) {
			$('#id_file_ico').addClass('disableInputText');
			$('#id_file_ico').removeClass('clickDialogOneDemo');
			$('#id_file_ico').attr('disabled','disabled');
			$('#file_icon_boxLink').css('display','none');
		}
		else {
			$('#file_icon_boxLink').css('display','block');
			$('#id_file_ico').attr('disabled','');
			$('#id_file_ico').addClass('clickDialogOneDemo');
			$('#id_file_ico').removeClass('disableInputText');
		}
		
	});


	//alert(tr.html());

    function createOfferRow(data, i, offer){
		
					var tr = $('<tr></tr>');
				
					var th1 = $('<td></td>').text(i+1+'.');
					if(data.file_file_name != null){
						var th2 = $('<td></td>').html(
						'<a class="facebox" target="_blank" href="' +url_variable+'icons/bigIcoGallery/'+data.account_public_folder+'/'+data.file_file_name+'">'+
						'<img src="'+url_variable+'icons/'+data.account_public_folder+'/'+data.file_file_name+'">'+
						'</a>'
						);
					}else{
						var th2 = $('<td></td>').html('<img src="'+url_variable+'images/noPhoto48.png">');
					}					
					var th3 = $('<td></td>').attr({'class':'bold file_name_td name'}).html(data.file_name+' ('+data.file_id+')'); 
					
					$(tr).append(th1).append(th2);
					
					//search form edit offerDetailTable
					var th3_sp = $('<span></span>').attr({'class':'infoOfferDetail'}).text('» pokaż szczegóły').click(function(){
						if ($(this).next('div').css('display') == 'none') {
							$(this).html('&raquo; ukryj szczegóły');
							$(this).next('div').fadeIn('fast');
						}
						else {
							$(this).html('&raquo; pokaż szczegóły');
							$(this).next('div').hide();
						}						
					});
					
					$(th3).append(th3_sp);

	
					
					var th3_div = $('<div></div>').attr({'class':'offerDetailTableDiv','style':'display: none'});
					
					var th3_div_tab = $('<table></table>').attr({'class':'search form edit offerDetailTable XXX'});					
					
					var th3_div_tab_tr1 = $('<tr></tr>');
					
					var th3_div_tab_tr1_td1 = $('<td></td>').attr({'class':'label'});
					var th3_div_tab_tr1_td1_label = $('<label></label>').text('Numer pliku')
					var th3_div_tab_tr1_td2 = $('<td></td>').text(data.file_id);
					
					$(th3_div_tab_tr1_td1).append(th3_div_tab_tr1_td1_label);
					$(th3_div_tab_tr1).append(th3_div_tab_tr1_td1).append(th3_div_tab_tr1_td2);
					$(th3_div_tab).html(th3_div_tab_tr1.html());
					
					
					var th3_div_tab_tr2 = $('<tr ></tr>');
					var th3_div_tab_tr2_td1 = $('<td ></td>').attr({'class':'label'});
					var th3_div_tab_tr2_td1_label = $('<label></label>').html('Platformy')
					var th3_div_tab_tr2_td2 = $('<td ></td>').html(data.file_platforms);
										
					$(th3_div_tab_tr2_td1).append(th3_div_tab_tr2_td1_label);
					$(th3_div_tab_tr2).append(th3_div_tab_tr2_td1).append(th3_div_tab_tr2_td2);
					$(th3_div_tab).append(th3_div_tab_tr2);					
										
					var th3_div_tab_tr3 = $('<tr ></tr>');
					var th3_div_tab_tr3_td1 = $('<td ></td>').attr({'class':'label'});
					var th3_div_tab_tr3_td1_label = $('<label></label>').html('Uwagi do pliku')
					var th3_div_tab_tr3_td2 = $('<td ></td>').html(data.file_info);
					
					$(th3_div_tab_tr3_td1).append(th3_div_tab_tr3_td1_label);
					$(th3_div_tab_tr3).append(th3_div_tab_tr3_td1).append(th3_div_tab_tr3_td2);
					$(th3_div_tab).append(th3_div_tab_tr3)
					
					if (data.file_producer_link.length > 0) {
						var th3_div_tab_tr4 = $('<tr ></tr>');
						var th3_div_tab_tr4_td1 = $('<td ></td>').attr({
							'class': 'label'
						});
						var th3_div_tab_tr4_td1_label = $('<label></label>').html('Link do strony producenta');
						var th3_div_tab_tr4_td2 = $('<td ></td>').html('<a href="'+data.file_producer_link+'">'+data.file_producer_link+'</a>');
						
						$(th3_div_tab_tr4_td1).append(th3_div_tab_tr4_td1_label);
						$(th3_div_tab_tr4).append(th3_div_tab_tr4_td1).append(th3_div_tab_tr4_td2);
						$(th3_div_tab).append(th3_div_tab_tr4);
					}
				
					$(th3_div).append(th3_div_tab);
					$(th3).append(th3_div);
				
					$(tr).append(th3);
					
					
					var th4 = $('<td></td>').text(data.amount_transactions);
					var th5 = $('<td></td>').text(data.file_platforms);
					var th6 = $('<td></td>').text(data.file_size);
					if(data.file_modify_date){
						var th7 = $('<td></td>').html(data.file_modify_date);
					}else{
						var th7 = $('<td></td>').html('-');
					}
					if (offer.offer_price > 0) {
						if(data.demo_file_id){
							var th8 = $('<td></td>').html('<a title="'+data.demo_file_name+'" href="/pobierz-demo/'+data.demo_file_id+'/'+offer.offer_id+'/" class="download"> </a>');
						}else{
							var th8 = $('<td></td>').html('-');
						}
						var th9 = $('<td></td>').attr({'class':'checkMe'}).html('<input class="check itemSubject" type="checkbox" name="itemId[]" value="'+data.offer_file_id+'" title="'+data.file_file_name+'"/>');
						var th10 = $('<td></td>').text(offer.offer_price+' zł');
						$(tr).append(th4).append(th5).append(th8).append(th6).append(th10).append(th7).append(th9);
					}else{
						var th8 = $('<td></td>').html('<a href="/pobierz-darmowy/'+offer.offer_id+'/'+data.offer_file_id+'/" class="download"> </a>');
						
						$(tr).append(th4).append(th5).append(th6).append(th7).append(th8);
					}			
									
					return tr;
					
		
	}
	
	function vIE(){return (navigator.appName=='Microsoft Internet Explorer')?parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):-1;}
	
	/*
	$('ul.menu_lvl1').superfish({
		   hoverClass:    'sfHover',
		   pathClass: 'current',
		   delay:       1000,                            // one second delay on mouseout 
           animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
           speed:       'slow',                          // faster animation speed 
           autoArrows:  false,                           // disable generation of arrow mark-up 
           dropShadows: false         
		 });
	*/
var img_number;
var img_numberString;


$('.imgSmall').click(function(){
	$('.imgBig').css('display','none');
	$('.imgBig_first').css('display','none');
	
	img_number=$(this).attr('rel');
	img_number=img_number.substring(9);
	//alert(img_number);
	img_numberString='.imgBig_'+img_number;
	//alert(img_numberString);
	$(img_numberString).css('display','inline');
});

$('.addFileToOfferButton').toggle(function(){
	$('.addFileToOffer').slideDown();
},function(){
	$('.addFileToOffer').slideUp();
})

$('table th input.check').click(
	function(){
		
		if ($(this).attr('checked')) {
			$(this).attr('checked', true);
			$(this).parent('th').parent('tr').parent('tbody').children('tr').each(function(){
				$(this).children('td.checkMe').children('input').attr('checked', true);
			})
		}
		
		if (!$(this).attr('checked')) {
			$(this).attr('checked', false);
			$(this).parent('th').parent('tr').parent('tbody').children('tr').each(function(){
				$(this).children('td.checkMe').children('input').attr('checked', false);
			})
		}
		
	});
//	},function(){
//	$(this).attr('checked','');
//	$(this).parent('th').parent('tr').parent('tbody').children('tr').each(function(){
//    	$(this).children('td.checkMe').children('input').attr('checked', false);
//    })
//	}
//);	



$('.logoChangeClick').click(function(){
	if ($('.logoUserChange').css('display')=='none')
	$('.logoUserChange').fadeIn();
	else
	$('.logoUserChange').fadeOut();
});
	
	
//	hiddenDesciptionOfferDetail
	$('.infoOfferDetail').click(function(){
		
		if ($(this).next('div').css('display') == 'none') {
			$(this).html('&raquo; ukryj szczegóły');
			$(this).next('div').fadeIn('fast');
		}
		else {
			$(this).html('&raquo; pokaż szczegóły');
			$(this).next('div').hide();
		}
	});
	
	/* File description Show */
	
	$('.infoBoxIco').hover(function(){
		$(this).parent().css('z-index','10');
	//	$(this).parent().parent().parent().parent().parent().parent().parent().css('z-index','100');
		var h = $(this).next().next('.hiddenDesciption').height();
		
		$(this).next().next('.hiddenDesciption').css('top','-'+(h+35)+'px')
		$(this).next().next('.hiddenDesciption').show();//fadeIn(); //css('display','block');
		
		
	}, function(){
		$(this).next().next('.hiddenDesciption').css('display','none');
	//	$(this).parent().parent().parent().parent().parent().parent().parent().css('z-index','1');
		$(this).next().parent().css('z-index','1')
		}
	);
	
	
	
	$.ui.dialog.defaults.bgiframe = true;

			
	function showOrHideAllDropDowns(newState) {
        
        var elements = document.documentElement.getElementsByTagName('select');
     
        for (var i=0; i<elements.length; i++) {
            elements[i].style.visibility = newState;
        }
    }	

/* DIALOG BOX - ICON TO FILE CHOOSE */
	
	var idString;
	var idStringName;
	
	$('.clickDialogOneIcon').click(function(){

	if (vIE()=='6'){ showOrHideAllDropDowns('hidden'); }
		
	$("#dialog").dialog({ 
		autoOpen: true,
        // resizable: false,
		// draggable: false,
        height: 650,
	    width: 995,//345,
        modal: true,
        title: 'Wybierz ikonę',
		zIndex: 3999,
        buttons: {
                'zapisz': function(){
					$(this).dialog('close');
                },
                'anuluj': function(){		 
					$('input.oneIconChoose').each(function(){
	  				if ($(this).attr('checked')) {
						$(this).attr('checked', false); 
					} }); $(this).dialog('close');}

            } 
	});
	
	$("#dialog").dialog('open'); 
	$('#dialog').bind('dialogbeforeclose', function(event, ui) {

			
	 var checkIconID; checkIconID='';
	 var checkIconTitle; checkIconTitle='';
	  
	  if (vIE()=='6'){ showOrHideAllDropDowns('visible'); }
	  
		 $('input.oneIconChoose').each(function(){
	  	if ($(this).attr('checked')) {
			checkIconID += $(this).val() + ';'; 
			checkIconTitle +=$(this).attr('title') + ';';
		}
	  });
			 
	 
	  $('#id_file_ico').val(checkIconTitle);
	  $('#id_file_id').val(checkIconID);
	});
	
	}); //$('.clickDialogIcon').click(function


/* DIALOG BOX - DEMO TO FILE CHOOSE */
	
	var idString;
	var idStringName;
	
	$('.clickDialogOneDemo').click(function(){

	if (vIE()=='6'){ showOrHideAllDropDowns('hidden'); }
		
	$("#dialogDemo").dialog({ 
		autoOpen: true,
        // resizable: false,
		// draggable: false,
        height: 640,
	    width: 995,//345,
        modal: true,
        title: 'Wybierz plik demo',
		zIndex: 3999,
        buttons: {
                'zapisz': function(){
					$(this).dialog('close');
                },
               'anuluj': function(){		 
					$('input.oneDemoChoose').each(function(){
	  				if ($(this).attr('checked')) {
						$(this).attr('checked', false); 
					} }); $(this).dialog('close');}

            } 
	});
	
	$("#dialogDemo").dialog('open'); 
	$('#dialogDemo').bind('dialogbeforeclose', function(event, ui) {

			
	 var checkDemoID; checkDemoID='';
	 var checkDemoTitle; checkDemoTitle='';
	  
	  if (vIE()=='6'){ showOrHideAllDropDowns('visible'); }
	  
		$('input.oneDemoChoose').each(function(){
	  	if ($(this).attr('checked')) {
			checkDemoID = $(this).val() + ';'; 
			checkDemoTitle =$(this).attr('title') + ';';
		}
	  });
			 
	  $('#id_file_demo').val(checkDemoTitle);
	  $('#file_id_demo').val(checkDemoID);
	});
	
	}); //$('.clickDialogIcon').click(function
	
/* DIALOG BOX - ICONS CHOOSE */
	
	var idString;
	var idStringName;
	
	$('.clickDialogIcon').click(function(){

	if (vIE()=='6'){ showOrHideAllDropDowns('hidden'); }
		
	$("#dialog").dialog({ 
		autoOpen: true,
        // resizable: false,
		// draggable: false,
        height: 650,
	    width: 995,//345,
        modal: true,
        title: 'Wybierz ikonę',
		zIndex: 3999,
        buttons: {
                'zapisz': function(){
					$(this).dialog('close');
                },
                'anuluj': function(){		 
					$('input.oneIconChoose').each(function(){
	  				if ($(this).attr('checked')) {
						$(this).attr('checked', false); 
					} }); $(this).dialog('close');}

            } 
	});
	
	$("#dialog").dialog('open'); 
	$('#dialog').bind('dialogbeforeclose', function(event, ui) {
	

//	var table=tablica.toString;

//	tablica.shift();
	idString=tablica.join();
//	idString=idString.substring(1);

	idStringName=tablicaName.join();
	
	//idStringName=idStringName.substring(1);
	//alert('tabl: '+tablicaFinal);
	
			
	 var allCheckID; allCheckID='';
	 var allCheckTitle; allCheckTitle='';
	  
	  if (vIE()=='6'){ showOrHideAllDropDowns('visible'); }
	  
		$('input.oneIconChoose').each(function(){
	  	if ($(this).attr('checked')) {
			idString += $(this).val() + ';'; 
			idStringName +=$(this).attr('title') + ';';
		}
	  });
		 
	  $('#id_file_ico').val(idStringName); 
	  $('#id_file_id').val(idString);
	});
	
	}); //$('.clickDialogIcon').click(function

	
	
/* DIALOG BOX - DEMOS CHOOSE */
	
	$('.clickDialogDemo').click(function(){
		if (vIE()=='6'){ showOrHideAllDropDowns('hidden'); }
		$("#demoDialog").dialog({ 
			autoOpen: true,
	        // resizable: false,
			// draggable: false,
	        height: 300,
		    width: 345,
	        modal: true,
	        title: 'Wybierz demo',
			zIndex: 3999,
	        buttons: {
	                'zapisz': function(){
						$(this).dialog('close');
	                }
	            }
		});
		$("#demoDialog").dialog('open'); 
		$('#demoDialog').bind('dialogbeforeclose', function(event, ui) {
			
		 var allDemosCheckID; allDemosCheckID='';
		 var allDemosCheckTitle; allDemosCheckTitle='';
    	  if (vIE()=='6'){ showOrHideAllDropDowns('visible'); }
		  
		  $('input.checkIconRadio').each(function(){
		  	if ($(this).attr('checked')) {
				allDemosCheckID += $(this).val() + ';'; 
				allDemosCheckTitle +=$(this).attr('title') + ';';
			}
		  });
				 
		  $('#id_file_demo').val(allDemosCheckTitle);
		  $('#file_id_demo').val(allDemosCheckID);
		});
	
	}); //$('.clickDialogIcon').click(function
	
/* DIALOG BOX - FILES CHOOSE */
	
	$('.clickDialogFiles').click(function(){

	if (vIE()=='6'){ showOrHideAllDropDowns('hidden'); }
		
	$("#filesDialog").dialog({ 
		autoOpen: true,
        // resizable: false,
		// draggable: false,
        height: 640,
	    width: 995,
        modal: true,
        title: 'Wybierz pliki',
		zIndex: 3999,
        buttons: {
                'zapisz': function(){
					$(this).dialog('close');
                }
            }
	});
	
	$("#filesDialog").dialog('open'); 
	$('#filesDialog').bind('dialogbeforeclose', function(event, ui) {
		
	 var allFilesCheckID; allFilesCheckID='';
	 var allFilesCheckTitle; allFilesCheckTitle='';
	  
	  if (vIE()=='6'){ showOrHideAllDropDowns('visible'); }
	  
	  $('input.checkFilesCheck').each(function(){
	  	if ($(this).attr('checked')) {
			allFilesCheckID += $(this).val() + ';'; 
			allFilesCheckTitle +=$(this).attr('title') + ';';
		}
	  });
	  
	idStringFiles=tablica2.join();
//	idStringFiles=idStringFiles.substring(1);
	
	idStringFilesName=tablicaName2.join();
	
	  $('#id_title_files').val(idStringFilesName);
	  $('#files_ids').val(idStringFiles);
	});
	
	}); //$('.clickDialogIcon').click(function	
	
/* DIALOG BOX - LICENSE CHOOSE */
	
	$('.clickDialogLicense').click(function(){

	if (vIE()=='6'){ showOrHideAllDropDowns('hidden'); }
		
	$("#licenseDialog").dialog({ 
		autoOpen: true,
        // resizable: false,
		// draggable: false,
        height: 590,
	    width: 995,
        modal: true,
        title: 'Wybierz licencję',
		zIndex: 3999,
        buttons: {
                'zapisz': function(){
					$(this).dialog('close');
                },
			  'anuluj': function(){		 
				$('input.checkLicenseCheck').each(function(){
  				if ($(this).attr('checked')) {
					$(this).attr('checked', false); 
				} }); $(this).dialog('close');}
            }
	});
	
	$("#licenseDialog").dialog('open'); 
	$('#licenseDialog').bind('dialogbeforeclose', function(event, ui) {
		
	 var allLicenseCheckID; allLicenseCheckID='';
	 var allLicenseCheckTitle; allLicenseCheckTitle='';
	  
	  if (vIE()=='6'){ showOrHideAllDropDowns('visible'); }
	  
	  $('input.checkLicenseCheck').each(function(){
	  	if ($(this).attr('checked')) {
			allLicenseCheckID += $(this).val() + ';'; 
			allLicenseCheckTitle +=$(this).attr('title') + ';';
		}
	  });
			 
	  $('#id_file_license').val(allLicenseCheckTitle);
	  $('#file_id_license').val(allLicenseCheckID);
	});
	
	}); //$('.clickDialogIcon').click(function	
		
	$('.registrationAccountType').change(function(){
		//if (this.val=='1') 
		
		if (this.value=='2') {
			$('.userRegistration').css('display','none');
			$('.firmRegistration').show();//.css('display','table-row');
			
			$('.AddrRegistration1').css('display','none');
			$('.AddrRegistration2').css('display','block');
			
		}
		
		if (this.value=='1') {
			$('.userRegistration').show();//.css('display','table-row');
			$('.firmRegistration').css('display','none');
			
			$('.AddrRegistration1').css('display','block');
			$('.AddrRegistration2').css('display','none');
		}
		
	}
	);
	
	
	$('.addFileFormType').change(function(){
		
		//if (this.val=='1') 
		if (this.value=='1' || this.value=='2') {
			$('.iconLicFormType').show();//.css('display','table-row');
			$('.demoFormType').css('display','none');
			$('.sellFormType').css('display','none');
		}
		
		if (this.value=='3') {
			$('.iconLicFormType').show();//.css('display','table-row');
			$('.demoFormType').show();//.css('display','table-row');
			$('.sellFormType').css('display','none');
		}
		
		if (this.value=='4') {
			$('.iconLicFormType').show();//.css('display','table-row');
			$('.demoFormType').show();//.css('display','table-row');
			$('.sellFormType').show();//.css('display','table-row');
		}
	}
	);
	
	$('.categoryAddButton').toggle(function(){   // obsluga dodawania ulubionych kategorii
		$('.categoryAddDiv').fadeIn();
		//$('.categoryAddDiv').css('display','block');
		//$('.categoryAddDiv').slideDown();
	}, function(){
		//$('.categoryAddDiv').css('display','none');
		$('.categoryAddDiv').slideUp();
	});
	
	jQuery('ul.menu_lvl1 li').toggle(function()
      {
	    jQuery(this).children('ul').slideDown();
		jQuery(this).children('ul').css('display', 'block');
      }, function(){
       jQuery(this).children('ul').slideUp();
	   });  
	   
	/* MASKED INPUTS */
	
	$("#account_post_code").mask("99-999");
	$("#account_post_code2").mask("99-999");
	$("#dateStartMainSearch").mask("9999-99-99"); 
	/*   
	//Superfish - default dynamic menu effect 
		$('ul.menuLeft').superfish({
		   hoverClass: 'active',
		   pathClass: 'current',
		   delay:       1000,                            // one second delay on mouseout 
           animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
           speed:       'normal',                          // faster animation speed 
           autoArrows:  false,                           // disable generation of arrow mark-up 
           dropShadows: false         
		 });
	*/
		 
}); // end ready function  
	
function getSubcategoriesList(Elem){
	
	idElem=$(Elem).attr('id');
	var myArray = idElem.split('_'); 
	var actual_level=myArray[2];
	
	acl = jQuery('#ajax_category_level').val();
	category = jQuery('#category_id_'+actual_level).val();
	acl2 = parseInt(acl)+1;

	var url_variable = jQuery('#url_variable').val();

	for(var i=parseInt(actual_level)+1;i<10;i++)
	{
		jQuery('#ajax_category_'+i).remove();
	}
	
    $.getJSON(url_variable+"index.php?mod=profile&scr=offers&evt=getSubCategories",{category_id:category}, function(json_obiekt){
		select_category ='<tr id="ajax_category_'+(parseInt(actual_level)+1)+'"> <td class="label"><label class="blue" for="category_id">Podkategoria: </label></td><td>';
		
		//alert(json_obiekt.length);
		if ((jQuery('#category_id_'+actual_level).val() != 0) && json_obiekt.length>0) {
			
    		select_category += '<select class="select" name="category_id_'+(parseInt(actual_level)+1)+'" id="category_id_'+(parseInt(actual_level)+1)+'" onchange="javascript:getSubcategoriesList(this)">';
			
			select_category +='<option value="0"> wybierz kategorię </option>';
		
	        i = 1;
	        for (key in json_obiekt) {
	            select_category += '<option value="' + json_obiekt[key][4] + '" >' + json_obiekt[key][0] + '</option>';
	            i++;
	        }
			
			select_category += '</select></td></tr>';
			
	      	jQuery('#ajax_category_level').val(parseInt(actual_level)+1);
	        jQuery('#ajax_category_'+actual_level).after(select_category);
		
		} else {
			jQuery('#ajax_category_level').val(parseInt(actual_level));
		}
		
		
		
    });
}

/*
 * by ivan
 */
function updateFlagShowRemoved(flag_name) {
	$('#submit_button').attr('disabled','disabled');
	
	if ($('#'+flag_name).attr('checked'))
		flag_value = 'true';
	else
		flag_value = 'false';
	
	$.ajax({
		type: 'POST',
		//zmienna url !!!
		url: url_variable + 'updateFlagShowRemoved',
		dataType: 'json',
		data: {
			flag_name: flag_name,
			flag_value: flag_value
		},
	  	success: function(data){       
			$('#submit_button').attr('disabled','');
		}
	});	
}

/*
 * by ivan
 */
function updateSelectedServices(service_id) {
	$('#submit_button').attr('disabled','disabled');
	
	if ($('#selected_service_' + service_id).attr('checked'))
		change = 'add';
	else
		change = 'remove';
   
	$.ajax({
		type: 'POST',
		//zmienna url !!!
		url: url_variable + 'updateAjaxSelectedService',
		dataType: 'json',
		data: {
			service_id: service_id,
			change: change
		}
	  	
	});	
}

function changePage() {
	if (!isNaN($('#pageNr').val())){
		var providedValue = $('#pageNr').val();
		if (providedValue > 0){
			document.location.href=$('#jump_link').val()+$('#pageNr').val();
		}
		else{
			alert('Podawana wartość musi być większa od 0.');
		}
	}
	else{
		alert('Podawana wartość musi być liczbą większą od 0.');
	}
		 	
}

function setIntervalAjax() {
	setInterval(function() {$.ajax({url: url_variable});}, 60*1000);
}

	/*
	//Facebox - gallery zoom 
	$('a[rel*=facebox]').facebox();
	$('img.obrazek').parent('a').facebox();
	
	//Transparency fix for IE6
	$.ifixpng('images/pixel.gif'); 
	$('img[@src$=.png],div#logo,.info_box2,.info_box').ifixpng();

	//Superfish - default dynamic menu effect 
		$('ul.submain').superfish({
		   hoverClass:    'sfHover',
		   pathClass: 'current',
		   delay:       1000,                            // one second delay on mouseout 
           animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
           speed:       'fast',                          // faster animation speed 
           autoArrows:  false,                           // disable generation of arrow mark-up 
           dropShadows: false         
		 });
		 
	//Superfish - default dynamic menu effect 
	
		$('ul.main').superfish({
		   hoverClass:    'sfHover',
		   pathClass: 'current',
		   delay:       1000,                            // one second delay on mouseout 
           animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
           speed:       'fast',                          // faster animation speed 
           autoArrows:  false,                           // disable generation of arrow mark-up 
           dropShadows: false         
		 });
		 
   $("#phone").mask("(999) 999-9999");
   
   $("#ssn").mask("999-99-9999");
   
	*/
	  




