var baseurl = "";
var lang = {}
lang["js_wallpaper_was_added_to_favourites"] = "Wallpaper was added to favourites"
lang["js_you_have_to_login_first"] = "You have to login first!"
lang["js_download_will_begin"] = "Your download will start in a few seconds. Please wait..."
lang["js_wallpaper_was_removed_from_fav"] = "Wallpaper was removed from favourites"
lang["js_voting_thank"] = "Thank you for voting!"
lang["js_type_a_message"] = "You have to type a message"
lang["js_comment_submit"] = "Thank you. Please allow 24 hours for reviewing your comment!"
lang["js_confirm"] = "Are you sure?"
var screenDetected = false;
$.extend($.ui.dialog.prototype, {
        'addbutton': function(buttonName, func) {
                var buttons = this.element.dialog('option', 'buttons');
                buttons[buttonName] = func;
                this.element.dialog('option', 'buttons', buttons);
        }
});
$.extend($.ui.dialog.prototype, {
        'removebutton': function(buttonName) {
                var buttons = this.element.dialog('option', 'buttons');
                delete buttons[buttonName];
                this.element.dialog('option', 'buttons', buttons);
        }
});

function addFlashNotif(msg,divDelay,refresh){
	if(!divDelay) divDelay = 3000;
	
	var display = $("#flashnotif").css('display');
	if (display == 'none') {
		$("#flashnotiftext").html(msg);
		$("#flashnotif").slideDown(function(){
			$(this).delay(divDelay).slideUp();
			if (refresh) {
				setTimeout('doRefresh()',1000);
			}
		});
	}
	else{
		$("#flashnotiftext").html(msg);
	}
}

$(function() {
	if ($("#refreshCaptcha").is('*')) {
		$("#refreshCaptcha").click(function(){
			var currentTime = new Date();
			var time = currentTime.getMilliseconds();
			$('#captcha').attr('src', baseurl + '/captcha/' + time);
			$('#captchaval').attr('value', '');
		});
	}
});

$(document).ready(function() {
    if(!screenDetected){
        screendetect();
    }
    
    if($("#wallpaperpage").is('*')){
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: baseurl + '/ajax/get_wallpaper_data',
            data: "wallpaper_id="+wallpaper_id,
            success: function(data){
                //$("#relatedwallpapers").html(data.related);
                $("#wallpaperallstats").after(data.stats);
                $("#wallpapervotes").html(data.votes);
            }
        });
        
        $("body").on('click','a.voteup',function(e){
            if(user_not_logged == true){
                addFlashNotif(lang['js_you_have_to_login_first']);
                return false;
            }
            e.stopPropagation();
            voteUp(wallpaper_id);
            return false;
        });
        
        $("body").on('click','a.votedown',function(e){
            if(user_not_logged == true){
                addFlashNotif(lang['js_you_have_to_login_first']);
                return false;
            }
            e.stopPropagation();
            voteDown(wallpaper_id);
            return false;
        });
    }
    
    $("body").on('click','a.resolutions-other-sizes',function(e){
        e.stopPropagation();
        $("ul.resolutions").toggle();
        return false;
    });
    if ( $.isFunction($.fn.tooltip) ) {
        $(".ttfav").tooltip({
            container: 'body'
        });

        $(".tt").tooltip({
            container: 'body'
        });
    }
    
    $("button#newsletter-submit").click(function(){
        var email = $("input#newsletter-email");
        var emailValue = $(email).val();
        
        $("#newsletter-holder").find('p.newsletter-message').remove();
        
        if(emailValue === ''){
            $(email).after('<p class="newsletter-message" style="color: #FF0000; font-size: 12px;">Please provide a valid email address!</p>');
            return false;
        }
        else{
            if(!validateEmail(emailValue)){
                $(email).after('<p class="newsletter-message" style="color: #FF0000; font-size: 12px;">Please provide a valid email address!</p>');
            }
            else{
                $.ajax({
                    type: "POST",
                    url: baseurl + '/ajax/newsletter',
                    data: "email="+emailValue,
                    success: function(data){
                        $("#newsletter-holder").html('<p><b>Thank you!</b><br>Subscription was successfull!</p>');
                        $("#newsletter-submit").remove();
                    },
                    error: function(e){
                        
                    }
                });
            }
        }
    });
    
    if ( $.isFunction($.fn.select2) ) {
        $(".sel2").select2({
            allowClear: true
        });
    }
    
    if ( $.isFunction($.fn.autosize) ) {
        if($(".wdescription").is('*')){
            $(".wdescription").autosize({append: "\n"});
        }
    }
    
    if($("input.dob").is('*')){
        $("input.dob").datepicker({
            dateFormat: 'yy-mm-dd',
            changeMonth: true,
            changeYear: true,
	});
    }
    
    if($("a.subscribe").is('*')){
        
        $.ajax({
            type: "POST",
            url: baseurl + '/ajax/get_subscription/'+ $("a.subscribe").attr('data-type'),
            data: {
                "value": $("a.subscribe").attr('data-value')
            },
            dataType: 'json',
            success: function(data){
                $("a.subscribe").text(data.name);
            },
            error: function(e){
                alert(e.responseText);
            }
        });
        
        $("body").on('click','a.subscribe',function(e){
            e.stopPropagation();
            
            $.ajax({
                type: "POST",
                url: baseurl + '/ajax/subscribe/'+$(this).attr('data-type'),
                data: {
                    "value": $(this).attr('data-value')
                },
                dataType: 'json',
                success: function(data){
                    $("a.subscribe").text(data.name);
                },
                error: function(e){
                    alert(e.responseText);
                }
            });
            
            return false;
        });
    }
    
    $("body").on("click", function (e){
        var container = $("#livesearch");
        
        if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            $('ul.livesearchresults li').remove();
            $("#qterm").val('');
        }
        
    });
    
    $("#qterm").keyup(function(){
        var qterm = $(this).val();
        if(qterm <= 2){
            $('ul.livesearchresults li').remove();
            return false;
        }
        $.ajax({
	   type: "POST",
	   url: baseurl + "/search/live",
	   data: "q=" + encodeURIComponent(qterm),
	   success : function (data){
               $("ul.livesearchresults").html(data);
	   }
	});
    });
    
    $("#wallpaper-title-suggestion").autocomplete({
        source: baseurl+"/api",
        minLength: 2,
        select: function (event, ui) {
            $("#wallpaper-title-suggestion").attr('value',ui.item.value);
        }
    });
});

function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 

function applyLoader(div){
	$(div).attr('class','loading');
	$(div).attr('value',$(div).attr('rel'));
}

function doRefresh(){
	document.location.href = document.location.href;
}

function screendetect(){
	$.ajax({
		type: "POST",
		url: baseurl + "/screendetect",
		data: "width=" + screen.width + '&height=' + screen.height,
		success: function(data){
                    $(".screendetect").replaceWith(data);
		}
	});
}

function setGlobalFilter(id){
	$.ajax({
		type: "POST",
		url: baseurl + "/screendetect/setglobalfilter",
		data: "id="+id,
		success: function(data){
			doRefresh();
		}
	});
        
        return false;
}

function unsetGlobalFilter(){
	$.ajax({
		type: "POST",
		url: baseurl + "/screendetect/unsetglobalfilter",
		data: "remove=1",
		success: function(data){
			doRefresh();
		}
	});
        return false;
}

function downloadWallpaper(obj,wid,rid,tid){
	addFlashNotif(lang['js_download_will_begin']);
	
	var form = '<form id="download" name="download" action="'+baseurl+'/dwnl" method="post">';
	form += '<input type="hidden" name="wid" value="'+wid+'" />';
	form += '<input type="hidden" name="rid" value="'+rid+'" />';
	form += '<input type="hidden" name="tid" value="'+tid+'" />';
	form += '</form>';
	$(obj).after(form);
	document.download.submit();
	$("#download").remove();
}

function scroll_to_div(id){
    id = id.replace("link", "");
    $('html,body').animate({
        scrollTop: $("#"+id).offset().top
	},'slow');
}

function favourites(obj,wid,onwpage){
    if(wid == 0){
        addFlashNotif(lang['js_you_have_to_login_first']);
        return false;
    }
    
    var fav = '.'+$(obj).parent().attr('class');
    if($(obj).hasClass('active')){
        $(fav).find('.favourite').removeClass('active');
        if(onwpage){
            $(fav).find('.favourite span.text').html('&nbsp;&nbsp;Add to Favourites');
        }
        else{
            $(fav).find('.favourite').attr('title', 'Add to Favourites').tooltip('fixTitle').tooltip('hide');
        }
        $.ajax({
	   type: "POST",
	   url: baseurl + "/favourites/remove",
	   data: "wid=" + wid,
	   success : function (data){
                addFlashNotif(lang['js_wallpaper_was_removed_from_fav']);
	   }
	});
    }
    else{
        $(fav).find('.favourite').addClass('active');
        if(onwpage){
            $(fav).find('.favourite span.text').html('&nbsp;&nbsp;Remove from Favourites');
        }
        else{
            $(fav).find('.favourite').attr('title', 'Remove from Favourites').tooltip('fixTitle').tooltip('hide');
        }
        $.ajax({
	   type: "POST",
	   url: baseurl + "/favourites/add",
	   data: "wid=" + wid,
	   success : function (data){
                addFlashNotif(lang['js_wallpaper_was_added_to_favourites']);
	   }
	});
    }
    
    return false;
}

function voteUp(wid){
	if(wid == 0){
		addFlashNotif(lang['js_you_have_to_login_first']);
		return false;
	}
	
	$.ajax({
	   type: "POST",
	   url: baseurl + "/votes/plus",
	   data: "wid=" + wid,
	   success : function (data){
	   		$(".votes").html(data);
			addFlashNotif(lang['js_voting_thank']);
	   }
	});
	
}

function voteDown(wid){
	if(wid == 0){
		addFlashNotif(lang['js_you_have_to_login_first']);
		return false;
	}
	
	$.ajax({
	   type: "POST",
	   url: baseurl + "/votes/minus",
	   data: "wid=" + wid,
	   success : function (data){
	   		$(".votes").html(data);
			addFlashNotif(lang['js_voting_thank']);
	   }
	});
}