$(document).ready(function() {
	$('ul#tabNavServices').find('a').bind('click',switchOrders);
	$('ul#tabNavArticles').find('a').bind('click',switchArticles);
	$('#newsletter a').click(showNewsletter);
	$('a.sendToFriendBtn').click(showSendToFriend);
	// linki do zewnetrznych serwisow w nowym oknie
	$('a[rel*="external"]').bind('click', function() {
	    $(this).attr('target', '_blank');
	    return true;
	});
    $('div.header-items form input[name=search_keywords]').bind('click', function(e) {
        if ($(this).val() == 'Znajdź coś dla Twego domu...' || $(this).val() == 'Znajdź coś dla Twojego ogrodu...') {
            $(this).val('');
        }
    });

    $('div.header-items form').bind('submit', function(e) {
        if ($(this).find('input[name=search]', 0).val() == 'Znajdź coś dla Twego domu...' || $(this).find('input[name=search]', 0).val() == 'Znajdź coś dla Twojego ogrodu...') {
            $(this).find('input[name=search]', 0).val('');
        }
    });
	// fancybox

    $('a[rel="fancybox"]').each(function() {
       this.href = '/api/showImage.php?src=' + this.href;
    });

    (af = $('a[rel="fancybox"]')).length && af.fancybox({
        titlePosition:'inside',
        type: 'iframe',
        scrolling:'no',
        titleFormat: function () {
            return this.orig && this.orig.attr && this.orig.attr('alt');
        },
        onComplete: function() {
            var iframe = $('#fancybox-content iframe');
            var wrapper = iframe.parent();

            iframe.load(function() {
                var img = $(this.contentDocument.body).find('img');
                var ratio = img.width() / img.height();

                var maxwidth = $(window).width() - 300;
                var maxheight = $(window).height() - 200;

                if(img.width() > maxwidth) {
                   img.width(maxwidth);
                   img.height(maxwidth / ratio);
                }

                if(img.height() > maxheight) {
                   img.height(maxheight);
                   img.width(maxheight * ratio);
                }

                var offsetWidth = img.width() - wrapper.width();

                wrapper.width(img.width());
                wrapper.height(img.height());
                $('#fancybox-title').width(img.width());

                var fancyWrap = $('#fancybox-wrap');

                fancyWrap.width(fancyWrap.width() + offsetWidth);
                $.fancybox.center(0);
            });
        }
    });

    //nadużycia
    $('a.postAbuse').click(function(e) {
        var postId = this.id.split('-')[1];

        var form = $('<form />')
            .addClass('defaultForm')
            .addClass('abuseForm');

        var fs = $('<fieldset />');
        form.append(fs);

        fs.append($('<label />').attr('for', 'abDesc').html('Treść:'));
        fs.append($('<textarea />').attr('id', 'abDesc').attr('rows', 4).attr('cols', 30).attr('maxlength', 300));
        fs.append($('<div/>').html('Podaj powód zgłoszenia'));

        jsAlert('<div id="abusePlaceholder"></div>', {
            title: 'Zgłoś nadużycie',
            buttons: {
                'Wyślij': function() {
                        var div = fs.find('div');
                        div.css('display', 'none');

                        var note = fs.find('textarea').val();

                        if(note == '') {
                            div.fadeIn(100);
                            return false;
                        }

                        $.post('/abuse.php', {
                            post_id: postId,
                            note: note
                        }, function(response) {
                            jsAlert(response.info, {title: 'Złoś nadużycie'});
                        },
                        'json'
                    );

                    $.modal.close();
                    return false;
                }
            }
        });

        var ph = $('div#abusePlaceholder');
        ph.parents('.simplemodal-container').addClass('abuseModal');
        ph.replaceWith(form);

        return false;
    });
});


function switchOrders()
{
	if ($(this).attr('id') == "tabServices"){
		$('#servicesTitle').html('Usługi budowlane');
		$('#servicesLink').attr('href','http://uslugi.forumbudowlane.pl');
		$('a#tabOffers').parent('li').removeClass('current');
		$(this).parent('li').addClass('current');
		$('div#ultabOffers').addClass('hide');
		$('div#ultabServices').removeClass('hide');
	} else if($(this).attr('id') == "tabOffers") {
		$('#servicesTitle').html('Zlecenia budowlane');
		$('#servicesLink').attr('href','http://zlecenia.forumbudowlane.pl');
		$('a#tabServices').parent('li').removeClass('current');
		$(this).parent('li').addClass('current');
		$('div#ultabServices').addClass('hide');
		$('div#ultabOffers').removeClass('hide');		
	}
	return false;
}

function switchArticles()
{
	if ($(this).attr('id') == "tabRead"){
		$('a#tabComment').parent('li').removeClass('current');
		$(this).parent('li').addClass('current');
		$('div#ultabComment').addClass('hide');
		$('div#ultabRead').removeClass('hide');
	} else if($(this).attr('id') == "tabComment") {
		$('a#tabRead').parent('li').removeClass('current');
		$(this).parent('li').addClass('current');
		$('div#ultabRead').addClass('hide');
		$('div#ultabComment').removeClass('hide');		
	}
	return false;
}

function showNewsletter() {
	$.ajax({
		url: '/newsletter.php',
		error: function() {
			jsAlert('Wystąpił nieoczekiwany błąd. Proszę spróbować za chwilę.');
	  	},
	  	success: function(html) {
	  		var root = $(html);
	  		$(document.body).append(root);
	  		setupOverlay();
	  		
	  		root.find('.close-box').click(function() {
	  			root.remove();
	  		});
	  		
	  		var form = root.find('form');
	  		form.submit(function() {
	  			$.ajax({
	  				url: '/newsletter.php',
	  				data: form.serializeArray(), 
	  				error: function() {
	  					jsAlert('Wystąpił nieoczekiwany błąd. Proszę spróbować za chwilę.');
	  			  	},
	  				success: function(ret) {
	  			  		if(ret.status == 'error') {
	  			  			root.find('.errorMsg').removeClass('hide');
	  			  			root.find('.errorTip').addClass('hide');
	  			  			root.find('.error').removeClass('error');
	  			  			
	  			  			for(var i = 0; i < ret.errors.length; i++) {
								root.find('.field-' + ret.errors[i]).addClass('error');
								root.find('.field-' + ret.errors[i] + ' .errorTip').removeClass('hide');
							}
	  			  		} else {
	  			  			root.remove();
	  			  			jsAlert('Na podany adres e-mail została wysłana wiadomość z linkiem aktywacyjnym. W celu aktywacji newslettera kliknij na wysłany link.');
	  			  		}
	  			  	},
	  			  	dataType: 'json'
	  			});
	  			
	  			return false;
	  		});
	  	},
	  dataType: 'html'
	});
	
	return false;
}


function showSendToFriend() {
	$.ajax({
		url: $('a.sendToFriendBtn').attr('href'),
		error: function() {
			jsAlert('Wystąpił nieoczekiwany błąd. Proszę spróbować za chwilę.');
	  	},
	  	success: function(html) {
	  		var root = $(html);
	  		$(document.body).append(root);
	  		setupOverlay();
	  		
	  		root.find('.close-box').click(function() {
	  			root.remove();
                return false;
	  		});

            root.find('form').submit(function() {
                root.find('.errorTip').addClass('hide');
                root.find('.field').removeClass('error');

                $.post(
                    $('a.sendToFriendBtn').attr('href'), 
                    $(this).serialize(), 
                    function(o) {
                        if(o.result) {
                            root.remove();
                            jsAlert('Wiadomość została wysłana.');
                        } else {
                            var msg = root.find('.msg.errorMsg');
                            msg.removeClass('hide');
                            msg.html(o.message);

                            if(o.field_errors) {
                                for(i in o.field_errors) {
                                    var fid = o.field_errors[i];

                                    root.find('.field-' + fid).addClass('error');
                                    root.find('.field-' + fid + ' .errorTip').removeClass('hide');
                                }
                            }
                        }
                    }, 
                    'json'
                );

                return false;
            });
	  	},
	  dataType: 'html'
	});
	
	return false;
}

function setupOverlay() {
	$('#overlay').css('height', document.body.scrollHeight + 'px');
}

function jsAlert(data, params) {

    var defParams = {}, html = '', bhtml = '', params = params || {}, b, x;

    defParams.title         = 'Wymagane potwierdzenie';
    defParams.width         = 320;
    defParams.height        = 100;
    defParams.containerCss  = {};

    defParams.buttons = {
        'Ok' : function() {
            $.modal.close();
            return false;
        }
    };

    $.extend(defParams, params);

    if(defParams.buttons) {

        bhtml = $('<div id="modalwindow-buttons">');

        for(b in defParams.buttons) {
            $(bhtml).append($('<a href="#" class="regBtn">'+b+'</a>').bind('click', defParams.buttons[b]));
        }
    }

    if(defParams.width) {
        defParams.containerCss.width = defParams.width;
    }

    if(defParams.height) {
        defParams.containerCss.height = defParams.height;
    }

    html = $('<div>');

    $(html).append('<div id="modalwindow-title">'+(defParams.title || '')+'</div>');
    $(html).append('<div id="modalwindow-content">'+(data || '')+'</div>');


    if(bhtml != '') {
        $(html).append(bhtml);
    }

    $.modal(html, defParams);
}

