$(document).ready(function() {
	shClubElements();
	shMainElements();
	checkDelFoto();
	checkDelete();
	formHelp();
	slide();
	ytmovies();
	googlemap();
	dragIt();
    checkBubble();
    captionImage();
    makeSlideShow();
});

function dragIt() {
    $('#icons img').draggable({
		cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
		revert: 'invalid', // when not dropped, the item will revert back to its initial position
		//containment: $('#img-map').length ? '#img-map' : 'document', // stick to demo-frame if present
		helper: 'clone',
		cursor: 'move',
		opacity: 0.7
	});
	 //let the trash be droppable, accepting the gallery items
	$('#img-map img').droppable({
		accept: '#icons > img',
		activeClass: 'ui-state-highlight',
		drop: function(ev, ui) {
		    getxy(ev,ui.draggable);
		    //var fa = ui.draggable.position();
		    //alert(ui.absolutePosition.left);
			//deleteImage(ui.draggable, ui.position.left, ui.position.top);
		}
	});
	
	function deleteImage($item, $left, $top) {
	    //var fa = $item.absoluteposition();
	    //$top = $item.absolutePosition.top;
	    //var left1 = $item.absolutePosition.left;
	    $item.clone().appendTo('#img-map');//.css({top: $top, left: $left, position: 'absolute'});
	}

}

function checkBubble() {
    if ($('.pin-bubble').length) {
        $.each($('.pin-bubble'), function() {
            var $this = $(this);
            var img_coord = $(this).attr('rel');
            var expl = img_coord.split(',');
            var x1 = parseInt(expl[0]);
            var y1 = parseInt(expl[1]);
            var img = expl[2];
            var usr = expl[3];
            
            if (usr > 0) {
				$('<div class="new-pin" />')
				.css({'background': 'url('+img+') 0 0 no-repeat'})
				.appendTo('#img-map')
				.css({top: y1, left: x1})
				.hover(function() {
					$('.pin-bubble').not($(this)).hide();
					$($this)
						.css({top: y1+27, left: x1})
						.show()
						.hover(function() { }, function() { $(this).hide(); });
				}, function() {
					//$($this).hide();
				})
				.click(function() {
					$('#pin_id').val(usr);
					$('#form-close').remove();
					$('#img-map #pin_desc').val($this.find('p').html());
					$('#img-map form').append('<span id="form-close">zamknij</span>');
					$('#img-map form').hide().css({top: y1+27, left: x1}).fadeIn(500);
					
					$('#img-map form a').remove();
					$('#img-map fieldset').append('<a href="'+$this.find('p').attr('rel')+'">usuń pinezkę</a>');
					$('#form-close').click(function() {
						$(this).parent().fadeOut(500);
					})
				});
            } else {
            	$('<div class="new-pin" />')
				.css({'background': 'url('+img+') 0 0 no-repeat'})
				.appendTo('#img-map')
				.css({top: y1, left: x1})
				.hover(function() {
					$('.pin-bubble').not($(this)).hide();
					$($this)
						.css({top: y1+27, left: x1})
						.show()
						.hover(function() { }, function() { $(this).hide(); });
				}, function() {
					//$($this).hide();
				})
            }
            /*$('#img-map form').click(function() {
                return false; 
            });*/
        })
    }
}

function getxy(e, ele) {
    mx = e.pageX;    // x position of mouse click
    my = e.pageY;    // y position of mouse click

    if(e.target)         // sets target element depending on browser type
		targ = e.target;
	else if(e.srcElement)
		targ = e.srcElement;
		
	x = 0;
	y = 0;

         //this while loop generates the offset of the element that was clicked
        // by looping through the parentElement until there is no more parent,
        // with each time getting the offset of the current element
        // this generates the offset of your element relative to the page.

	while(targ.offsetParent)
	{
		y = y + targ.offsetTop;
		x = x + targ.offsetLeft;
		targ = targ.offsetParent;
	}

        // subtract mouse coordinate clicks from element offset variables
	ix = mx - x;
	iy = my - y;
	ele.clone().appendTo('#img-map').css({top: iy, left: ix, position: 'absolute'});
	
    //$('#coor').html('X: '+ix+', Y '+iy);
    //$('<div class="new-pin" />').appendTo('#img-map').css({top: iy, left: ix});
    $('#img-map form a').remove();
    $('#form-close').remove();
    $('#icons').css({visibility: 'hidden'});
    $('#img-map form').css({top: iy+27, left: ix}).show().find('fieldset').append('<span id="form-cancel">anuluj</span>');
    $('#pin_desc').val('').focus();
    $('#pin_coord').val(ix+','+iy);
    $('#pin_img').val(ele.attr('src'));
    $('#form-cancel').click(function() {
        $('#img-map form').fadeOut(500);
        $('#img-map #form-cancel').remove();
        $('#img-map .ui-draggable:last-child').remove();
        $(this).remove();
        $('#icons').css({visibility: 'visible'});
        return false;
    })
    //$('<div class="pin-bubble"><h5>Opis</h5></div>').appendTo('#img-map').attr('rel', ix+','+iy);
}

function captionImage() {
	if ($('.captiongal').length > 0) {
		var move = -15,
			zoom = 1.2
		
		$('.captiongal li').hover(function() {
			width = $('.captiongal li').width() * zoom;
			height = $('.captiongal li').height() * zoom;
			$(this).find('img').stop(false,true).animate({'width':width, 'height':height, 'top':move, 'left':move}, {duration:200});
			$(this).find('.caption').stop(false,true).fadeIn(200);
		}, function() {
			$(this).find('img').stop(false,true).animate({'width':$('.captiongal li').width(), 'height':$('.captiongal li').height(), 'top':'0', 'left':'0'}, {duration:200});
			$(this).find('.caption').stop(false,true).fadeOut(200);
		}).click(function() {
			window.location = $(this).find('a').attr('href');
			return false;
		})	
	}
}


function slide() {
	//console.log($('.longtext').outerHeight(true), $('.shorttext').outerHeight(true));
	if ($('.longtext').length > 0) {
		var h_long = $('.longtext').outerHeight(true);
		var h_short = $('.shorttext').outerHeight(true);
		$('.slide .longtext').hide();
		if (h_long > h_short) {
			$('.slide').append('<span class="more">więcej</span>');
			$('.slide .more').toggle(function() {
				$('.shorttext').hide();
				$('.longtext').css({display: 'block'});
				$(this).html('zwiń');
			}, function() {
				$('.longtext').hide();
				$('.shorttext').css({display: 'block'});
				$(this).html('więcej');
				$(document).scrollTo("#pagecontent", 1000);
			});
		}	
	}
}

// formhelp script -------------------------------------------------
function formHelp(){
	$("label span").css({position:"relative"});
	$("label em").addClass("formhelp").hide();
	$("label img").css({display:"inline"}).hover(
		function(){
			$(this).parent().parent().find("em").show();
		}, function(){
			$(this).parent().parent().find("em").hide();
		}
	);
}

// usuwanie fotek
function checkDelFoto(){
	$("p.deletefoto").find("a").click(function(){
		return confirm("Czy na pewno chcesz usunąć zdjęcie?");
	});
}

// usuwanie wpisow
function checkDelete(){
	$("a.delete").click(function(){
		return confirm("Czy na pewno chcesz usunąć wpis?\nOperacja jest nieodwracalna!");
	});
}

// main
function shMainElements(){
	$("p.maininfo a:first").addClass("active");
	$("div.maininfotext").hide();
	$("div.maininfotext:first").show();
	$("p.maininfo a").attr("href","javascript:void(null)").click(function(){
		$("p.maininfo a.active").removeClass("active");
		$(this).addClass("active");
		var rel = $(this).attr("rel");
		$("div.maininfotext").hide();
		$("div."+rel).show();
	});
}

// kluby
function shClubElements(){
	$("p.clubinfo a:first").addClass("active");
	$("div.clubinfotext").hide();
	$("div.clubinfotext:first").show();
	$("p.clubinfo a").attr("href","javascript:void(null)").click(function(){
		$("p.clubinfo a.active").removeClass("active");
		$(this).addClass("active");
		var rel = $(this).attr("rel");
		$("div.clubinfotext").hide();
		$("div."+rel).show();
	});
	$("p.partyinfo a:first").addClass("active");
	$("p.partyinfotext").hide();
	$("p.partyinfotext:first").show();
	$("p.partyinfo a").attr("href","javascript:void(null)").click(function(){
		$("p.partyinfo a.active").removeClass("active");
		$(this).addClass("active");
		var rel = $(this).attr("rel");
		$("p.partyinfotext").hide();
		$("p."+rel).show();
	});
}

// pokaż współrzędne siedziby klubu
function showAddress() { 
	geocoder = new GClientGeocoder();
	if (geocoder) {
		var city = document.getElementById('city').value; 
		var address = document.getElementById('address').value; 
		var place = city+', '+address;
    	geocoder.getLatLng(
        	place,
          	function(point) {
            	if (!point) {
              		alert(place + " nie istnieje");
				} else {
					//map.setCenter(point, 13);
					//map.clearOverlays();
	      			//map.addOverlay(new GMarker(point));
	      			document.getElementById("mglat").value = point.y;
	      			document.getElementById("mglng").value = point.x;
				}
			}
		);
	}
}

// pokaz mapke google z wspolrzednymi zapisanimi w ukrytym polu formularza, pobranimi z bazy danych
function googlemap() {
	var ma = document.getElementById("googlemap");
	if(ma){
		if (GBrowserIsCompatible()) { 
			lat = parseFloat(document.getElementById("googlemapdaddr").value.split(",")[0]);
			lng = parseFloat(document.getElementById("googlemapdaddr").value.split(",")[1]);
			map = new GMap2(ma); 
       			map.setCenter(new GLatLng(lat, lng), 8);
		  	map.addOverlay(new GMarker(new GLatLng(lat, lng),{title : "To nasz adres"}));
		  	map.addControl(new GSmallMapControl());
		  	map.addControl(new GMapTypeControl());	
		  	map.addControl(new GOverviewMapControl());	
		}	
	}
}

function ytmovies() {
    if ($('#ytholder').length) {
        $("ul#ytlist").ytplaylist({playerHeight: 350, playerWidth: 400, autoPlay: false, holderId: 'ytvideo'});
    }
}

function makeSlideShow() {
    var startId = 'photo_' + $('#MySlideshow').attr('rel');
    var startIndex = 0;
    $('#MySlideshow li').each(function(index) {
      if ($(this).attr('id') == startId) {
        startIndex = index;
        return false;
      }
    });
    $('#MySlideshow').slideShow({sliderValue: 6000, index: startIndex});
}
