$(document).ready(function() {

    /* dropdown community
     $(".lr_community").hover(
     function () {
     $(".landrover_communities_wrapper").animate({
     marginTop: "-8px",
     opacity:1
     },200);
     },
     function () {
     $(".landrover_communities_wrapper").animate({
     marginTop:'-170px',
     opacity:0
     },200);
     }
     );*/

    /* fancybox standart */
    $("a.pops").fancybox({
        'hideOnContentClick': false,
        'hideOnOverlayClick': false,
        'overlayOpacity'    :    0.6,
        'overlayColor'    :    '#000',
        'scrolling'    :    'hidden',
        'padding'    : 0
    });


    $("a.pops-wo-close").fancybox({
        'hideOnContentClick': false,
        'hideOnOverlayClick': false,
        'overlayOpacity'    :    0.6,
        'overlayColor'    :    '#000',
        'scrolling'    :    'hidden',
        'padding'    : 0,
        'enableEscapeButton' : false,
        'showCloseButton' : false
    });


    $("a.author-feedback-pop").fancybox({
        'hideOnContentClick': false,
        'hideOnOverlayClick': false,
        'overlayOpacity'    :    0.6,
        'overlayColor'    :    '#000',
        'scrolling'    :    'hidden',
        'padding'    : 0,
        onComplete      : function() {
            var url = $('.__currentUrl').val();
            $('#r_addr').val(url);

            var imageSrc = $('.__currentPhotoSrc').val();
            $('#r_photo').val(imageSrc);
        }
    });

    /* show/hide slidefilters */
    $("h1.h_filters").click(function() {
        var par = $(this).parents(".fs_tgl");
        var tar = $(this).next("#in_fs");
        $(par).toggleClass("tgl_closed");
        if ($(par).hasClass("tgl_closed")) {
            $(tar).animate({
                height: 1,
                opacity: 0
            }, 200, function() {

                var mapHeight = $("#map_container").height();
                $("#main_map").height(mapHeight);
            });
        }
        else {
            $(tar).animate({
                height: 114,
                opacity: 1
            }, 200, function() {

                var mapHeight = $("#map_container").height();
                $("#main_map").height(mapHeight);
            });
        }

    });

    /* show/hide tags */
    var tcHeight = $("#tag_cloud").height();

    $("#tag_cloud").height(1);

    $("#tc_cont .open_tc").click(function() {
        $("#tag_cloud").removeClass("hidden").animate({
            height: tcHeight + "px",
            opacity: 1
        }, 200);
    });
    $("#tc_cont .close_tc").click(function() {

        if ($(this).parents('.map-tags-show').size() > 0) {
            var mapShow = $(this).parents('.map-tags-show');

            $("#tag_cloud").removeClass("hidden").animate({
                height: tcHeight + "px",
                opacity: 1
            }, 200);

            mapShow.removeClass('map-tags-show');

            return false;
        }

        if ($('#map_tags_opened').size() > 0) {
            $("#tag_cloud").animate({
                height: "34px",
                opacity: 1
            }, 250);

            $('#tag_cloud').addClass('map-tags-show');
        } else {
            $("#tag_cloud").animate({
                height: "1px",
                opacity: 0
            }, 250);
        }
    });


    if ($('#map_tags_opened').size() > 0) {
        $("#tag_cloud").removeClass("hidden").animate({
            height: 34,
            opacity: 1
        }, 30);
    }

    /* add/remove tag */
    var lTag = $("#tag_cloud .tags li a");
    var aTags = $("#tag_cloud .added_tags .at_list");
    var aTagsVal = '';

    $(lTag).click(function(e) {
        var name = $(this).attr('name');

        if ($('span[name="' + name + '"]', aTags).size() > 0) {
            return false;
        }

        var lTagCont = $(this).html();
        e.preventDefault();

        $(aTags).append('<span name="' + name + '">' + lTagCont + '<a href="#" class="removeTag">[x]</a></span>');


        if ($('span', aTags).size() > 0) {

            $('.__tags_reset').val('0');
            $('.help_cont_wrapper').attr('id', 'map_tags_opened');

            if ($('#tag_cloud').hasClass('hidden')) {
                $('#tag_cloud').addClass('map-tags-show');
                $('#tag_cloud').removeClass('hidden');
            }

            aTagsVal = '';

            $('span', aTags).each(function(key) {
                var text = $(this).text().replace('[x]', ', ');

                aTagsVal = aTagsVal + text;

                $('.__tags_input').val(aTagsVal);
            })


        } else {

            $('.help_cont_wrapper').removeAttr('id');

            if ($('#tag_cloud').hasClass('map-tags-show')) {
                $('#tag_cloud').addClass('hidden');
                $('#tag_cloud').removeClass('map-tags-show');
            }

            $(aTags).text('');
            $('.__tags_input').val('');
            $('.__tags_reset').val('1');

        }
    });

    $("#tag_cloud .added_tags .removeTag").live("click", function(removeTag) {
        removeTag.preventDefault();
        $(this).parents('span').remove();

        if ($('span', aTags).size() > 0) {

            aTagsVal = '';
            $('span', aTags).each(function() {
                var text = $(this).text().replace('[x]', ', ');


                aTagsVal = aTagsVal + text;

                $('.__tags_input').val(aTagsVal);
            })


        } else {
            $(aTags).text('');
            $('.__tags_reset').val('1');
            $('.__tags_input').val('');
        }

    });

    $("#tag_cloud .added_tags .tl_clear a").live("click", function(removeAllTags) {
        removeAllTags.preventDefault();
        $(aTags).html('');

        $(aTags).text('');
        $('.__tags_input').val('');
        $('.__tags_reset').val('1');
        
    });

    /*
     if($("#tag_cloud .added_tags span").size() > 0) {
     $("#tc_cont .open_tc").trigger('click');
     }*/

    /* remove photo preview*/

    /*
     $("#previewBox div i").live("click", function() {
     $(this).parent('div').remove();
     var apc_quo = $("#previewBox div").length;
     if (apc_quo == 0) {
     $("#up_cont .btn_upload").removeClass("hidden");
     $("#up_cont .btn_upload_more").addClass("hidden");
     }
     else {

     $("#up_cont .btn_upload").addClass("hidden");
     $("#up_cont .btn_upload_more").removeClass("hidden");
     }
     });*/


    $("#previewBox div i").live("click", function() {
        $(this).parents('.files-row').remove();
        initAddForm();
    });

    /* No feedback */

    $(".unreg #community_block span.mail_us a.unreg_link").click(function() {
        $(this).next("i.no_feedback").fadeIn(250);
    });
    $(".unreg #community_block span.mail_us i.no_feedback").mouseout(function() {
        $(this).delay(350).fadeOut(250);
    });

    $(".unreg #footer div.left a.unreg_link").click(function(noFeedback) {
        noFeedback.preventDefault();
        $(this).next("p.no_feedback").fadeIn(250);
    });
    $(".unreg #footer div.left p.no_feedback a").click(function() {
        $(".unreg #footer div.left p.no_feedback").delay(350).fadeOut(250);
    });
    $(".unreg #footer div.left p.no_feedback a.go_auth").click(function() {
        $("#input-login").focus();
    });


    $('.tags-linl-tr').bind('click', function(e) {
        e.preventDefault();

        $('#map_tags_opened i.close_tc').trigger('click');
        $.scrollTo('#footer');
    });

    $('.btn_clear').bind('click', function() {
        $(this).hide();
        $('#search .field-label').show();
    });

    $('#search_f').bind('keyup keydown', function() {

        if ($(this).val() != '') {
            $('.btn_clear').show();
        } else {

            $('.btn_clear').hide();
        }
    })


    if ($('#addForm').size() > 0) {
        var filesFormsCount = 0;
        function initAddForm() {
            initAjaxForm(
                $('#addForm'),
                '/addplace.php',
                function(oForm, oData) {
                    if (oData.result['success'] == false) {

                        return false;
                    }
                    lockForm(oForm);

                    $('.add_success_lb_trigger').trigger('click');

                    return;
                }
            );
        }

        initAddForm();

        $('.files-add .add_photo_button').bind('click', function(e) {
            e.preventDefault();


            if (filesFormsCount == 7) {
                return;
            }

            $('.files-inputs').append('' +
                '<div class="files-row files-row-new">' +
                '<h2>Новое фото &nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="files-add-cancel">Удалить</a></h2>' +
                '<div class="file-field">' +
                '<input type="file" name="file[]" class="input_file"/>' +
                '</div>' +
                '<div class="add-info">' +
                '<dl class="zf-required author">' +
                '<dt><label for="r_fio">Автор:</label></dt>' +
                '<dd><input class="zf field" type="text" name="file_author[]" id="r_fio" onclick="return { oRequired : { iMin : 2 }, oOptions : { iMaxLength : 50  } }" maxlength="50"/></dd>' +
                '</dl>' +
                '<dl class="zf-required author">' +
                '<dt><label for="file_source">Источник:</label></dt>' +
                '<dd><input class="zf field" type="text" name="file_source[]" id="file_source" onclick="return { oRequired : { iMin : 2 }, oOptions : { iMaxLength : 1000  } }" maxlength="1000"/></dd>' +
                '</dl></div>' +
                '</div>' +
                '')

            if ($.browser.msie) {
                $('.files-row-new:last').show();
            } else {
                $('.files-row-new:last').fadeIn(300);
            }

            $('#addForm input[type=submit]').customDisableSubmit($('#addForm'));

            $('.files-inputs input').bind('change keyup', function() {
                val = $(this).val();
                if (val && val.length > 2) {
                    $(this).parents('dl').removeClass('zf-required');
                    $('#addForm input[type=submit]').customEnableSubmit($('#addForm'));
                } else {
                    $(this).parents('dl').addClass('zf-required');
                    $('#addForm input[type=submit]').customDisableSubmit($('#addForm'));
                }
            });

            filesFormsCount++;

            if (filesFormsCount == 7) {
                $('.files-add').hide();
            }
        });

        $('.files-add-cancel').live('click', function(e) {
            e.preventDefault();

            $(this).parents('.files-row').fadeOut(300).remove();

            if (filesFormsCount == 7) {
                $('.files-add').show();
            }

            if(checkForm($('#addForm'))) {

                $('#addForm input[type=submit]').customEnableSubmit($('#addForm'));
            } else {
                $('#addForm input[type=submit]').customDisableSubmit($('#addForm'));
            }

            filesFormsCount--;
        });

        $('#addForm .files-inputs .add-info input.field').live('change keyup', function(){
            val = $(this).val();

            if (val && val.length > 2) {
                $('#addForm input[type=submit]').customEnableSubmit($('#addForm'));
            } else {
                $('#addForm input[type=submit]').customDisableSubmit($('#addForm'));
            }
        });


    }


    /* Profile logic */

    var fileInput = $('#pr_file');

    var dropBox = $('#imgContainer');

    fileInput.live({
        change: function() {
            displayFiles(this.files);
        }
    });

    dropBox.live({
        dragenter: function() {
            $(this).addClass('highlighted');
            return false;
        },

        dragover: function() {
            return false;
        },

        dragleave: function() {
            $(this).removeClass('highlighted');
            return false;
        },

        drop: function(e) {
            var dt = e.originalEvent.dataTransfer;
            displayFiles(dt.files);
            return false;
        }
    });

    function displayFiles(files) {
        var imgList = $('#imgContainer');
        $.each(files, function(i, file) {
            if (!file.type.match(/image.*/)) {
                return true;
            }

            // Создаем элемент li и помещаем в него название, миниатюру и progress bar,
            // а также создаем ему свойство file, куда помещаем объект File (при загрузке понадобится)
            $('img', imgList).remove();
            $('div', imgList).remove();

            var li = $('<div />').appendTo(imgList);
            var img = $('<img/>').appendTo(li);
            li.get(0).file = file;


            // Создаем объект FileReader и по завершении чтения файла, отображаем миниатюру и обновляем
            // инфу обо всех файлах
            var reader = new FileReader();
            reader.onload = (function(aImg) {
                return function(e) {
                    aImg.attr('src', e.target.result);
                    aImg.attr('width', 150);
                    /* ... обновляем инфу о выбранных файлах ... */
                };

            })(img);

            reader.readAsDataURL(file);

            $('#EditProfileForm input[type=submit]').trigger('click');
        });

    }

    /*
     $('.btn_logout a').live('click', function(e){
     e.preventDefault();

     var aRef = $(this).attr('href');
     $('body').toggleClass('authd').addClass('unreg');
     $('#layout').toggleClass('authorized').addClass('unreg');

     $.get(aRef);
     })*/






	$('#banner_block a').bind('click', function(e){
		e.preventDefault();

		var ref = $(this).attr('href');

		var bclass = $(this).attr('class');

		if(bclass == 'landroverru') {
			_gaq.push(['_trackPageview', '/link/landroverru']);
			yaCounter11354566.reachGoal("/link/landroverru");
			//console.log(ref);
		}

		if(bclass == 'landroverexperience') {
			_gaq.push(['_trackPageview', '/link/landroverexperience']);
			yaCounter11354566.reachGoal("/link/landroverexperience");
			//console.log(ref);
		}

		if(bclass == 'helloevoque') {
			_gaq.push(['_trackPageview', '/link/helloevoque']);
			yaCounter11354566.reachGoal("/link/helloevoque");
			//console.log(ref);
		}

		if(bclass == 'landroverexpeditions') {
			_gaq.push(['_trackPageview', '/link/landroverexpeditions']);
			yaCounter11354566.reachGoal("/link/landroverexpeditions");
			//console.log(ref);
		}

		if(bclass == 'jlrconnect') {
			_gaq.push(['_trackPageview', '/link/jlrconnect']);
			yaCounter11354566.reachGoal("/link/jlrconnect");
			//console.log(ref);
		}

		window.open(ref);
	});

    var __SERVER_NAME__ = window.location.host;
    if($('.comment_subj').size() > 0) {
        $('.comment_subj').each(function(){
            $('a', this).each(function(){
                var ref = $(this).attr('href');
                if(ref) {
                    var url = $(this).url();
                    var protocol = url.attr('protocol');
                    var host = url.attr('host');
                    var isMail = ref.match(/^mailto/) ? true : false;
                    if(host && !protocol && !isMail) {
                        var ref = $(this).attr('href');
                        ref = 'http://' + ref;
                        $(this).attr('href', ref);
                    }

                    if((host && host != __SERVER_NAME__ && !$(this).attr('target') && !$(this).attr('target') != '_blank') || isMail) {
                        $(this).attr('target', '_blank');
                        $(this).attr('rel', 'nofollow');
                    }
                }
            })
        })
    }

});


