var windowWidth = document.documentElement.clientWidth;
var windowHeight = window.pageYOffset;
popupPhotoOpen = false;
/**
 * Function get json object and show message if isn't empty.
 */
function callback_json_parse(obj) {
    if(obj!=null) {
        if (obj.code != null && obj.code != 1) {
            if (obj.title == null) {
                obj.title = i18n.error_title;
            }
            if(obj.no_popup == null){
                if (obj.message != null && obj.message != '') {
                    showPopup(obj.title, obj.message);
                    $('#popup_ok').focus();
                }
                return null;
            }
        } else if ((obj.code != null && obj.code == 1)) {
            if (obj.title == null) {
                obj.title = 'Info';
            }
            if(obj.no_popup == null)
                if (obj.message != null && obj.message != '') {
                    showPopup(obj.title, obj.message);
                    $('#popup_ok').focus();
                }
        }
        return true;
    } else {
        return null;
    }
}

/**
 * Function show popup with given title and text
 */
var showPopup = function(title, text) {
    var scrollPosition = window.pageYOffset;
    $('#popup_title').html(title);
    $('#popup_text').html(text);
    $('#popup').css({
        'display' : 'block'
    });
    $('#popup_overlay').css({
        'display' : 'block'
    })
    $('#popup_ok').focus();
    $(document).keydown(function(e) {
        var code = (event.keyCode ? event.keyCode : event.which);
        if (code == 27) {
            closePopup();
        }
    })
}

var showPopupPhoto = function(title,text) {
    if(popupPhotoOpen==false) {
        popupPhotoOpen = true;
        var scrollPosition = window.pageYOffset;
        $('#popupPhotoTitle').html(title);
        $('#popupPhotoText').html(text);
        $('#popupPhoto').css({
            'display' : 'block'
        });
    }

//    $('#popupPhoto_overlay').css({
//        'display' : 'block'
//    })
//    $(document).keydown(function(e) {
//        if (e.keyCode == 27) {
//            closePopup();
//        }
//    })
}
resultAddress = '';
var showLayerPhoto = function(title,text) {
    if(popupPhotoOpen==false) {
        popupPhotoOpen = true;
        $('#col_middle').children().remove();

        $('#col_middle').prepend('<div id="layerPhotoUpload"><div id="layerPhotoUploadTitle"></div><div id="layerPhotoUploadText"></div></div>');
        $('#layerPhotoUploadResult').hide();
        resultAddress = '';
        $('#layerPhotoUploadTitle').html(title);
        $('#layerPhotoUploadText').html(text);
    }

//    $(document).keydown(function(e) {
//        if (e.keyCode == 27) {
//            closePopup();
//        }
//    })
}

//$('body').live('dblclick',function() {
//showLayerPhoto("Tytul","Tresc");
//});

var closePopup = function() {
    $('#popup').css({
        'display' : 'none'
    });
    $('#popup_overlay').css({
        'display' : 'none'
    })
    $('#popup_title').html('');
    $('#popup_text').html('');
}
var closePopupPhoto = function() {
    $('#popupPhoto').css({
        'display' : 'none'
    });
    popupPhotoOpen=false;
    $('#popupPhoto_overlay').css({
        'display' : 'none'
    })
    $('#popupPhotoTitle').html('');
    $('#popupPhotoText').html('');
}
var closeLayerUploadPhoto = function() {
    $('#col_middle').children().show();
    $('#layerPhotoUpload').remove();
    popupPhotoOpen=false;
//    $('#layerPhotoUploadTitle').html('');
//    $('#layerPhotoUploadText').html('');
}

$('#popup_ok').live('click', function() {
    closePopup();
});
$('#layerPhotoUploadOk').live('click', function() {
    closeLayerUploadPhoto();
});
$('#popupPhotoOk').live('click', function() {
    closePopupPhoto();
});
$('#popup_overlay').live('click', function() {
    closePopup();
});

var block_page = function(element) {
	
    if (element) {
        $(element).block({
            message : i18n.please_wait + '...<div class="loader"><div class="image"></div></div>'
        });
    } else {
        $('.welcome, .tos').block({
            message : i18n.please_wait + '...<div class="loader"><div class="image"></div></div>'
        });
    }
}

var unblock_page = function(element) {
    if (element) {
        $(element).unblock({
            message : i18n.please_wait + '...<div class="loader"><div class="image"></div></div>'
        });
    } else {
        $('.welcome, .tos').unblock({
            message : i18n.please_wait + '...<div class="loader"><div class="image"></div></div>'
        });
    }
}

$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [ o[this.name] ];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(document)
    .ready(
        function() {
            $('#comment_form > a').click(
                function(eve) {
                    eve.preventDefault();
                    var url = $(this).attr('href');
                    $.ajax({
                        type : "GET",
                        url : url,
                        data : ({}),
                        dataType : 'json',
                        beforeSend : function() {
                        },
                        success : function(html) {
                            $('#comment_form > a.show_form').hide();
                            if (html.error) {
                                $('#comment_form').append(
                                    '<p>error: ' + html.code
                                    + '</p>');
                            } else {
                                $('#comment_form').append(html.html);
                                $('#comment_form .fp_comment').focus();
                            }
                        }
                    });
                });

            $('#comment_form > div.form a.close').live('click',
                function(eve) {
                    eve.preventDefault();
                // $('#comment_form > a.show_form').show();
                // $('#comment_form > div.form').remove();
                });

            $('#comment_form > div.form form')
            .live(
                'submit',
                function(eve) {
                    eve.preventDefault();
                    var form_block = $(this).closest(
                        'div.form');
                    var url = $(this).attr('action');
                    var dataString = $(this)
                    .serializeObject();
                    $
                    .ajax({
                        type : "POST",
                        url : url,
                        data : {
                            data : dataString
                        },
                        dataType : 'json',
                        beforeSend : function() {
                            form_block
                            .block({
                                css : {
                                    width : '50%'
                                },
                                message : '<div class="loader"><div class="image"> </div></div>'
                            });
                        },
                        success : function(obj) {
                            break_callback = callback_json_parse(obj);
                            if (break_callback == null) {
                                form_block
                                .unblock();
                                return;
                            }
                            $('#comment_form > a.show_form')
                            .show();
                            //$('#comment_form > div.form')
                            //.remove();
                            if (obj.html != null) {
                                $('#comments #comment_content')
                                .prepend(
                                    obj.html
                                    );
                            } else {
                                if (obj.error != null)
                                    $('#comment_form')
                                    .append(
                                        obj.error);
                            }
                            $('#comment_content textarea').higit_textarea_expander();

                            // unblock textarea
                            form_block
                            .unblock();
                            //cleaning content in textarea
                            $('#comment_form > div.form [name=\'comment\']').val('');
                            $('#comment_form > div.form [name=\'comment\']').attr('style','height: 50px; overflow: hidden; padding-top: 0px; padding-bottom: 0px; width: 365px;');
                        },
                        error : function() {
                            form_block.unblock();
                        }
                    });
                });

            $('a.logout').click(function(eve) {
                eve.preventDefault();
                var post = false;
                // keep the target address
                var href = $(this).attr('href');
                
                if(typeof(isUploader)!= 'undefined' && isUploader) {
                    valConfirm = confirm(i18n.unload_error);
                    if(valConfirm) {
                        isUploader = false;
                    } else {
                        return false;
                    }
                }
                // block body during logout
                block_page('body');
                
                // if user was logged in facebook
                if(typeof(FB)!= 'undefined') {
	                // logout from facebook
	                FB.getLoginStatus(function(response) {
	                    if (response.authResponse) {
	                        FB.logout(function(response) {
	                            $.post(href, function(data) {
	                                // redirect to default area
	                                window.location.href=_config.base_url;
	                            });
	                        });
	                    } else {
	                        $.post(href, function(data) {
	                            // redirect to default area
	                            window.location.href=_config.base_url;
	                        });
	                    }
	                    
	                },true);
                } else {
                	$.post(href, function(data) {
                            // redirect to default area
                            window.location.href=_config.base_url;
                        });
                }

            })

            $('div.fb-login-button').click(function(eve) {
                eve.preventDefault();
                block_page('body');
                var login_cb = function(response) {
                    if (response.status === 'connected') {
                        window.location.reload(0);
                    } else {
                        window.location.reload(0);
                    }
                };
            })

   
            $('#suggestion_form')
            .live(
                'submit',
                function(eve) {
                    eve.preventDefault();
                    var form_block = $(this).closest(
                        'div.menu_box');
                    var url = $(this).attr('action');
                    var dataString = $(this).serializeObject();
                    var text = $('#suggestions_textarea').val();
                    $.ajax({
                        type : "POST",
                        url : url,
                        data : {
                            data : dataString
                        },
                        dataType : 'json',
                        beforeSend : function() {
            	
                            if ( (text == "") || (text == i18n.suggestion_default) ) {
                                showPopup(i18n.error_title, i18n.suggestion_sended_error);
                                $('#suggestions_textarea').focus();
                                return false;
                            }
            	
                            form_block.block({
                                css : {
                                    width : '50%'
                                },
                                message : '<div class="loader"><div class="image"> </div></div>'
                            });
                        },
                        success : function(obj) {
                            break_callback = callback_json_parse(obj);
                            if (break_callback == null) {
                                form_block.unblock();
                                return;
                            }
                
                            if (obj.html != null) {
                                showPopup(i18n.ok_title, obj.html);
                            } else {
                                if (obj.error != null)
                                    $('#comment_form').append(obj.error);
                            }
                            // unblock textarea
                            form_block.unblock();
                            //cleaning content in textarea
                            $('#suggestions_textarea').val(i18n.suggestion_default);
                            $('#suggestions_textarea').attr('style','display: block; margin: 10px 0 10px 0; width: 128px;');
                        },
                        error : function() {
                            form_block.unblock();
                        }
                    });
                });
    
            $('#suggestions_textarea').click(function(eve) {
                var text = $('#suggestions_textarea').val();
                if ( (text != "") || (text != i18n.suggestion_default) ) {
                    $(this).empty();
                }
            });

            $('#h_plus_button').click(function(eve){
                eve.preventDefault();
                var url;
                if($(this).hasClass('unlike')){
                    url = '/h/like_object/higit_minus/'+photo_og;
                }else {
                    url = '/h/like_object/higit_plus/'+photo_og;
                }
                $.ajax({
                    type: "POST",
                    dataType : 'json',
                    url: url,
                    data: "h="+hash_og,
                    success: function(msg){
                        if(typeof(msg.h_count) != 'undefined'){
                            $('#photo_like .higit_count').html(msg.h_count);
                            if(msg.like == 1){
                                $('#h_plus_button').addClass('unlike');
                                Tipped.remove('#content #h_plus');
                            } else {
                                $('#h_plus_button').removeClass('unlike');
                            }
                        }
                    }
                }); 
            });

            $('a.h_plus_comment').live('click',function(e){
                e.preventDefault();
                anchor = $(this);
                var url = $(this).attr('href');
                if(!$(this).hasClass('added')){
                    $.ajax({
                        type: "POST",
                        dataType : 'json',
                        url: url,
                        success: function(obj){
                            if(obj.code == 1){
                                $(anchor).attr('title',obj.h_count);
                                $(anchor).addClass('added');
                                $(anchor).html(obj.h_count);
                            }
                        }
                    });
                }
            })

        });
//!!!!! end document ready

$(".photo_desc").live('submit', function(event) {
    event.preventDefault();
});
//    form = $(this);
//    url = $(this).attr('action');
//    dataString = $(this).serializeObject();
//    $.ajax({
//        type : "POST",
//        url : url,
//        data : {
//            data : dataString
//        },
//        dataType : 'json',
//        beforeSend : function() {
//
//        },
//        success : function(obj) {
//            break_callback = callback_json_parse(obj);
//            if (break_callback == null)
//                return;
//            $(form).closest('.wraper').remove();
//        }
//    });
//});

/**
 * function save description and title for photo.
 */
//var savePhotoDesc = function(obj) {
//    $(obj).closest('.form').removeClass('saved');
//    $(obj).closest('.form').addClass('progress');
//    desc = $(obj).val();
//    if($(obj).hasClass("grayInput")) {
//        desc = '';
//    }
//    obj = $(obj).closest('form');
//    form = obj;
//    id=form.find('input[name="id"]').val();
//    h=form.find('input[name="h"]').val();
//    type=form.find('input[name="type"]').val();
//    url = $(obj).attr('action');
//    dataString = 'description='+desc+'&id='+id+'&h='+h+'&type='+type;//$(obj).serializeObject();
//    $.ajax({
//        type : "POST",
//        url : url,
//        data : dataString,
//        dataType : 'json',
//        beforeSend : function() {
//
//        },
//        success : function(result) {
//            break_callback = callback_json_parse(result);
//            if (break_callback == null)
//                return;
//            $(obj).closest('.form').removeClass('progress');
//            $(obj).closest('.form').addClass('saved');
//        },
//        error : function(result) {
//            break_callback = callback_json_parse(result);
//            if (break_callback == null)
//                return;
//            $(obj).closest('.form').removeClass('progress');
//            $(obj).closest('.form').addClass('saved');
//        }
//    });
//}

//var photoDescInterval = 2000;
//
///**
// * When key is down in input for description or title, change class
// */
//$('.photo_desc .input textarea').live('keydown',
//function(e) {
//    $(this).closest('.form').removeClass('saved');
//});

/**
 * When key is up in input for description or title, start timer and then save
 * photo description and title
 */
//$('.photo_desc .input textarea').live(
//'keyup',
//function() {
//    // cleanTagInput(this);
//    // eval('var CurrA = $.merge([], A' + getEID(this) + ');');
//    var detailId = $(this).closest('.form').find('input[name="id"]')
//    .val();
//    eval('var photoDescTimer = photoDescTimer' + detailId + '');
//    clearTimeout(photoDescTimer);
//    var obj = this;
//    photoDescTimer = setTimeout(function() {
//        savePhotoDesc(obj)
//    }, photoDescInterval);
//    eval('photoDescTimer' + detailId + ' = photoDescTimer');
//    // getTags(getEID(this), $(this).val())}
//});

/**
 * Click action on spam_link
 */
$('a.spam_link').live('click', function(event) {
    event.preventDefault();
    obj = $(this);
    form = obj;
    url = $(obj).attr('href');
    // dataString = $(obj).serializeObject();
    $.ajax({
        type : "GET",
        url : url,
        data : {},
        dataType : 'json',
        beforeSend : function() {

        },
        success : function(result) {
            break_callback = callback_json_parse(result);
            if (break_callback == null)
                return;
            $(obj).attr('id','');
            $(obj).html(result.html); 
            
        }
    });
    return false;
})

/**
 * Click action on violation_link
 */
$('a.violation_link').live('click', function(event) {
    event.preventDefault();
    obj = $(this);
    form = obj;
    url = $(obj).attr('href');
    // dataString = $(obj).serializeObject();
    $.ajax({
        type : "GET",
        url : url,
        data : {},
        dataType : 'json',
        beforeSend : function() {

        },
        success : function(result) {
            break_callback = callback_json_parse(result);
            if (break_callback == null)
                return;
            $(obj).attr('id','');
            $(obj).html(result.html);

        }
    });
    return false;
})


/**
 * Click action on object to higlight him.
 */
$('a.object_highlight').live('click', function(event) {
    event.preventDefault();
    var answer = confirm('Czy aby na pewno chcesz wyróżnić zdjęcie?');
    if (answer) {
        obj = $(this);
        form = obj;
        url = $(obj).attr('href');
        // dataString = $(obj).serializeObject();
        $.ajax({
            type : "GET",
            url : url,
            data : {},
            dataType : 'json',
            beforeSend : function() {

            },
            success : function(result) {
                break_callback = callback_json_parse(result);
                if (break_callback == null)
                    return;
                $(obj).html(result.html);
            }
        });
        return false;
    }
})

/**
 * Remove (or make censored) object by adminnistrator.
 */
$('a.object_to_remove').live('click', function(event) {
    event.preventDefault();
    var answer = confirm('Czy aby na pewno chcesz usunąć?');
    if (answer) {
        obj = $(this);
        form = obj;
        url = $(obj).attr('href');
        // dataString = $(obj).serializeObject();
        $.ajax({
            type : "GET",
            url : url,
            data : {},
            dataType : 'json',
            success : function(result) {
                break_callback = callback_json_parse(result);
                if (break_callback == null)
                    return;
                $(obj).removeClass('object_to_remove');
                $(obj).addClass('object_removed');
                $(obj).html(result.html);

            }
        });
        return false;
    }
});

$('a.object_removed').live('click', function(event) {
    event.preventDefault();
});


/***********************************************************
 ****************** LOGIN POPUP FUNCTION SET ***************
 ***********************************************************/
var tos_accepted =0;
$('#accept_terms').live('submit',function(event){
    event.preventDefault();
    var dataString = $(this).serializeObject();
    var url = $(this).attr('action');
    block_page();
    $.ajax({
        type : "POST",
        url : url,
        data : dataString,
        dataType : 'json',
        success : function(obj) {
            break_callback = callback_json_parse(obj);
            if (break_callback == null) {
                unblock_page();
                //if tos_accept post failed allow another post
                tos_accepted=0;
                return;            
            }
            // registration limit reached
            if(obj.code == 711){
                if(obj.url != null){
                    block_page();
                    $.get(obj.url, function(data) {
                        $('#popup_login').html(data);
                    });
                }
            }else
            if(obj.code == 1){
                window.location.reload(true);
            }
        },
        error: function(){
            //if tos_accept post failed allow another post
            tos_accepted=0;
        }
    });
    return false;
});


$('#create_account').live('click',function(event){
    if(tos_accepted == 0){
        tos_accepted = 1;
        $(this).closest('#accept_terms').submit();
    }

});

String.prototype.br2nl = function() {
    var nl;
    if( typeof arguments[0] != 'undefined' ) {
        nl = arguments[0];
    }
    else {
        nl = '\n';
    }
    return this.replace( /\<br(\s*\/|)\>/g, nl );
}



