$(document).ready(function() {
    checkIPhone();
    initLinks();
});

function checkIPhone() {
    if (navigator.userAgent.match(/AppleWebKit/i) && navigator.userAgent.match(/Mobile/i)) {
        //	alert('Is it iPhone, iPod or iPad?');
        $('body').addClass('iphone');
    }
}


function englishOnlyVal(oWidget) {
    var fValue = oWidget.getValue().mValue;
    var re = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
    if (fValue) {
        return re.test(fValue);
    } else {
        return false;
    }
}


function profilePasswordVal(oWidget) {
    var fValue = oWidget.getValue().mValue;

    if (fValue.length && fValue.length < 6) {
        return false;
    } else {
        return true;
    }
}


$.fn.customDisableSubmit = function(oForm) {
    $(this).attr('disabled', 'disabled');
    $(this).addClass('zf-disabled');
}

$.fn.customEnableSubmit = function(oForm) {
    if (checkForm(oForm)) {
        $(this).removeAttr('disabled', 'disabled');
        $(this).removeClass('zf-disabled');
    } else {
        $(this).customDisableSubmit();
    }
}


$('#EditProfileForm #r_pass').live('keyup', function() {
    var oFormWidget = $('#EditProfileForm'); //;ZForms.getFormById('EditProfileForm');
    var val = $(this).val();
    var newPassVal = $('#EditProfileForm #r_pass_new').val();
    var newPassConfirm = $('#EditProfileForm #r_pass_confirm').val();
    if (!val && !newPassVal && !newPassConfirm) {
        $('#profileFormSubmit').customEnableSubmit(oFormWidget);
        return 1;
    }

    if (val && val.length > 5) {

        if (newPassVal && newPassVal.length > 5) {
            if (newPassConfirm && newPassConfirm.length > 5) {
                $('#profileFormSubmit').customEnableSubmit(oFormWidget);
            }

        } else {
            $('#profileFormSubmit').customDisableSubmit(oFormWidget);
        }
    } else {
        $('#profileFormSubmit').customDisableSubmit(oFormWidget);
    }
});


$('#EditProfileForm #r_pass_new').live('keyup', function() {
    var oFormWidget = $('#EditProfileForm'); //;ZForms.getFormById('EditProfileForm');
    var val = $(this).val();
    var newPassVal = $('#EditProfileForm #r_pass').val();
    var newPassConfirm = $('#EditProfileForm #r_pass_confirm').val();

    if (!val && !newPassVal && !newPassConfirm) {
        $('#profileFormSubmit').customEnableSubmit(oFormWidget);
        return 1;
    }

    if (val && val.length > 5) {
        if (newPassVal && newPassVal.length > 5) {
            if (newPassConfirm && newPassConfirm.length > 5) {
                $('#profileFormSubmit').customEnableSubmit(oFormWidget);
            }
        } else {
            $('#profileFormSubmit').customDisableSubmit(oFormWidget);
        }
    } else {
        $('#profileFormSubmit').customDisableSubmit(oFormWidget);
    }
});


$('#EditProfileForm #r_pass_confirm').live('keyup', function() {
    var oFormWidget = $('#EditProfileForm'); //;ZForms.getFormById('EditProfileForm');
    var val = $(this).val();
    var newPassVal = $('#EditProfileForm #r_pass').val();
    var newPassConfirm = $('#EditProfileForm #r_pass_new').val();

    if (!val && !newPassVal && !newPassConfirm) {
        $('#profileFormSubmit').customEnableSubmit(oFormWidget);
        return 1;
    }


    if (val && val.length > 5) {
        if (newPassVal && newPassVal.length > 5) {
            if (newPassConfirm && newPassConfirm.length > 5) {
                $('#profileFormSubmit').customEnableSubmit(oFormWidget);
            }
        } else {
            $('#profileFormSubmit').customDisableSubmit(oFormWidget);
        }
    } else {
        $('#profileFormSubmit').customDisableSubmit(oFormWidget);
    }
});


function alphaNumVal(oWidget) {
    var fValue = oWidget.getValue().mValue;
    var re = /^[а-яa-z- ]+$/i;
    if (fValue) {
        return re.test(fValue);
    } else {
        return false;
    }
}

function initLinks(oBlock) {
    var oLinks = null;
    if (oBlock && oBlock.length) {
        oLinks = oBlock.find('.hoverable');
    } else {
        oLinks = $('.hoverable');
    }
    initLinksHover(oLinks);
//	initLinksSelect(oLinks);
}

function parse_hash() {
    var hash = window.location.hash.replace("#", "");
    return hash;
}

function initLinksHover(oLinks) {
    oLinks
        .removeClass('hoverable')
        .mouseenter(function() {
            $(this).addClass('hover');
        })
        .mouseleave(function() {
            $(this).removeClass('hover').removeClass('waiting');
        })
        .mousedown(function() {
            $(this).addClass('waiting');
        })
        .mouseup(function() {
            $(this).removeClass('waiting');
        })
        ;
}

jQuery.fn.toggleAttr = function(attr) {
    return this.each(function() {
        var $this = $(this);
        $this.attr(attr) ? $this.removeAttr(attr) : $this.attr(attr, attr);
    });
};

(function ($) {
    $.fn.vAlign = function() {
        return this.each(function(i) {
            var ah = $(this).height();
            var ph = $(this).parent().height();
            var mh = Math.ceil((ph - ah) / 2);


            $(this).css('margin-top', mh);
        });
    };
})(jQuery);


(function ($) {
    $.fn.enlargeYourImage = function() {
        $("a.enlarge_your_image").fancybox({
            'hideOnContentClick': false,
            'hideOnOverlayClick': true,
            'overlayOpacity'    :    0.6,
            'overlayColor'    :    '#000',
            'scrolling'    :    'hidden',
            'padding'    : 0
        });
    };
})(jQuery);


(function ($) {
    $('.btn_rss').bind('click', function() {
        var loc = $(this).find('a').attr('href');

        window.location = loc;
    });

    $.fn.initPopups = function() {
        $(this).fancybox({
            'hideOnContentClick': false,
            'hideOnOverlayClick': false,
            'overlayOpacity'    :    0.6,
            'overlayColor'    :    '#000',
            'scrolling'    :    'hidden',
            'padding'    : 0,
            'onComplete' : function() {
            }
        });
    }

    $("a.pops").initPopups();

    $('#community_auth span.fb a').live('click', function() {
        $('.fb_button').trigger('click');
    });

    $.fn.appendComment = function(data) {
        var link = data['USER_LINK'] ? '<a href="' + data['USER_LINK'] + '" class="' + data['LINK_CLASS'] + '">' + data['USER_NAME'] + '</a>' : '<span class="text-name">' + data['USER_NAME'] + '</span>';
        var html = '<div class="comment_item"><img class="userpic left" src="' + data['USER_PHOTO'] + '" /><p class="left user-name">' + link + '<span class="comment-time">' + data['COMMENT_DATE'] + '</span></p><p class="comment_subj">' + data['COMMENT_TEXT'] + '</p><p class="reply"><a href="#">Ответить</a></p></div>';
        $(this).append(html);

        var comsVal = parseInt($('#place_post .links p a.coms').text());

        if (!comsVal) {
            comsVal = 0;
        }

        var newComsVal = comsVal + 1;
        $('#place_post .links p a.coms').text(comsVal + 1);
        $('.stat_comments big').html(newComsVal + '<br><span>комментариев</span>');
    }

    $('.comment_item .reply a').live('click', function(e) {
        e.preventDefault();
        var authorName = $(this).parents('.comment_item').find('.user-name .text-name').text();

        $('#comment-form textarea').val("@" + authorName + ", ").focus();
        $('#comment-form textarea').scrollTo();
    })


    $('.scroll-to-comment').live('click', function(e) {
        e.preventDefault();

        $('#comment-form textarea').focus();
    });

    if ($('#comment-form textarea').size() > 0) {
        $('#comment-form textarea').val('');
    }


    var profilePicObj = $('input[name=r_file]');

    if (profilePicObj.size() > 0) {
        profilePicObj.live('change', function() {
            var val = $(this).val();
            var valArr = val.split("\\");


            var file = valArr[2] ? valArr[2] : valArr;


            if (file) {
                if ($('span.filename').size() > 0) {
                    $('span.filename').remove();
                }

                $('<span class="filename">Загрузка...</span>').insertAfter(this);
            }

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


    var xhr_key = 0;
    var fxhr = new Array;


    $('#pl_filter a').live('click', function(e) {
        e.preventDefault();

        if ($(this).parents('.show_toggle').size() > 0) {
            return;
        }


        $('#pl_filter a:hidden').next('span').toggleClass('hidden');
        $('#pl_filter a:hidden').toggleClass('hidden');


        $(this).next('span').toggleClass('hidden');
        $(this).toggleClass('hidden');


        var ajaxRef = $(this).attr('href');
        xhr_key++;


        fxhr[xhr_key] = $.ajax({
            url: ajaxRef,
            beforeSend: function(xhr) {
                $('.items-list-loader').fadeIn();
            },
            success: function(data) {
                $('.items-list-wrapper').html(data);
                $('.items-list-loader').resize_ilist_loader();
                $('.items-list-loader').fadeOut(250);
            }
        });


        if (fxhr[xhr_key - 1]) {
            fxhr[xhr_key - 1].abort();
            delete fxhr[xhr_key - 1];
        }
    });

    $('.show_toggle a').live('click', function(e) {
        e.preventDefault();


        $('.show_toggle a').removeClass('active');
        var index = $(this).index() - 1;

        $('.show_toggle a:eq(' + index + ')').addClass('active');


        var ajaxRef = $(this).attr('href');
        xhr_key++;


        fxhr[xhr_key] = $.ajax({
            url: ajaxRef,
            beforeSend: function(xhr) {
                $('.items-list-loader').fadeIn();
            },
            success: function(data) {

                $('.items-list-loader').fadeOut(250);
                $('.items-list-loader').resize_ilist_loader();
                $('#in_pl .items-list-wrapper').html(data);
            }
        });


        if (fxhr[xhr_key - 1]) {
            fxhr[xhr_key - 1].abort();
            delete fxhr[xhr_key - 1];
        }
    });


    $('#in_pl .paginator a').live('click', function(e) {
        e.preventDefault();


        $('#in_pl .paginator a').removeClass('active');
        $(this).addClass('active');


        var ajaxRef = $(this).attr('href');
        xhr_key++;


        fxhr[xhr_key] = $.ajax({
            url: ajaxRef,
            beforeSend: function(xhr) {
                $('.items-list-loader').fadeIn();
            },
            success: function(data) {
                $('.items-list-loader').resize_ilist_loader();
                $('.items-list-loader').fadeOut(250);
                $('#in_pl .items-list-wrapper').html(data);
            }
        });


        if (fxhr[xhr_key - 1]) {
            fxhr[xhr_key - 1].abort();
            delete fxhr[xhr_key - 1];
        }
    });


    $('.reset-search').live('click', function(e) {
        e.preventDefault();

        var ajaxRef = $(this).attr('href');
        xhr_key++;


        fxhr[xhr_key] = $.ajax({
            url: ajaxRef,
            beforeSend: function(xhr) {
                $('#SearchForm .btn_clear').trigger('click');
                $('#search_f').val('').trigger('change');
                $('#search .field-label').show();
                $('.items-list-loader').fadeIn();
                $("#tag_cloud .added_tags .tl_clear a").trigger('click');
            },
            success: function(data) {
                if(ajaxRef != '/get_places_list.php?reset_search=1') {
                    if(ajaxRef != '/get_places_list.php?reset_tags=1') {
                        window.location.reload();
                    } else {
                        var urlArr = window.location.href.split('?');

                        if(urlArr[1] && urlArr[1].match(/by_tag/)) {
                            window.location = '/places/';
                        } else {
                            window.location.reload();
                        };
                    }
                } else {
                    window.location = '/places/';
                }



                /*
                $('.items-list-loader').resize_ilist_loader();
                $('.items-list-loader').fadeOut(250);

                $('#in_pl .items-list-wrapper').html(data);
                $('.search-query').removeClass('search-query-show');
                $('.tags-search-query').removeClass('tags-search-query-show');

                $('#places_list h1').removeClass('search-results');*/

                
            }
        });


        if (fxhr[xhr_key - 1]) {
            fxhr[xhr_key - 1].abort();
            delete fxhr[xhr_key - 1];
        }
    });


    $.fn.resize_ilist_loader = function() {
        var parent_block_h = $('.items-list-wrapper').height();
        var parent_block_w = $('.items-list-wrapper').width();

        $(this).height(parent_block_h);
        $(this).width(parent_block_w);
    }

    $(window).bind('load resize', function() {
        if ($('.items-list-loader').size() > 0) {
            $('.items-list-loader').resize_ilist_loader();
        }
    });


    $.fn.resizeMap = function() {
        var mapHeight = $("#map_container").height();
        var bodyHeight = $(window).height();
        
        
        if (bodyHeight < 800) {
            var headerHeight = $('#header').height();
            var footerHeight = $('#footer_wrapper').height();
            var mapHeight = bodyHeight;
        }
        $("#main_map").height(bodyHeight-177);
        $('.loading_map_info').height(mapHeight);
		
		
		
        $('.loading_map_info .loading-text').css('margin-top', mapHeight / 2);
    }


    $.fn.setRating = function() {
        var ajaxRef = $(this).attr('href');
        var obj = this;

        $(obj).addClass('disabled');

        $.ajax({
            url: ajaxRef,
            dataType: 'json',
            beforeSend: function(xhr) {
            },
            success: function(data) {
                if (data && data.result) {
                    $('.rating-wrapper').html(data.result);
                }
            }
        });
    }

    $('.set-rating-button').live('click', function(e) {
        e.preventDefault();

        if (!$(this).hasClass('disabled')) {
            $(this).setRating();
        }
    })

    $('.lb-close-button').live('click', function(e) {
        e.preventDefault();
        $('#fancybox-close').trigger('click');
    })


})(jQuery);


$(function() {

    /* Place info map link generation */
    function generateGPSLink(gpsArr) {
        return  '#placeGps=true&lat=' + gpsArr['lat'] + '&lng=' + gpsArr['lng'];
    }

    $.fn.generateMapLink = function() {

        if ($('input.__gpsArr').size() > 0) {
            var gpsArr = {
                'lat' : $('input.__gpsLat').val(),
                'lng' : $('input.__gpsLng').val()
            };

            var link = generateGPSLink(gpsArr);
            var addParams = '';
            if ($(this).parent().hasClass('btn_map')) {
                addParams = '&fromPlacePage=1';
            } else {
                addParams = '';
            }
            var placeId = $('input.__placeID').val();
            addParams += '&id=' + placeId;
            var ref = $(this).attr('href') + '?fromDetail=1' + addParams;
            ref = ref + link;

            $(this).attr('href', ref);
        }
    }
    if ($('#place_about').size() > 0) {

        /*
         if(document.referrer.match(/map/g)) {
         $('.btn_back a').generateMapLink();
         }*/

        $('.btn_map a, .addr-link').generateMapLink();
    }

    if ($.browser.msie) {
        $('#SearchForm #search_f').bind('keypress', function(e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if (code == 13) {
                $('#SearchForm input[type=submit]').trigger('click');
            }
        });
    }

    $('#LoginForm .field').live('click focus change keyup', function() {
        $(this).prev('label').hide();
    });

    $('#LoginForm .field').live('focusout blur', function() {
        if (!$(this).val()) {
            $(this).prev('label').show();
        }
    });


    $('#SearchForm .field').live('click focus change keyup', function() {
        $(this).prev('label').hide();
    });

    $('#SearchForm .field').live('focusout blur', function() {
        if (!$(this).val()) {
            $(this).prev('label').show();
        }
    });


    $('#LoginForm .field').each(function() {

        if ($(this).val()) {
            $(this).prev('label').hide();
        }
    });


    if($.browser.webkit) {
        $('.field-label').each(function(){

            var text = $(this).text();
            $(this).next('input').attr('placeholder', text);
            $(this).remove();

        });
    }

})
/*
 function initLinksSelect(oLinks){
 oLinks.click(function(){
 $(this).html($(this).html());
 });
 }
 */
