var bubbleTimer =  null;
var bubbleOver = false;
var mywindow;
$(document).ready(function(){

	if ($.browser.msie)
		$.fx.off = true;
    
    $.validator.addMethod("username", function(value, element){
            var re = /\W/;
            return !re.test(value);
        }, "Only alphabets, numbers and underscore are allowed.");
        
	$(".bubble").hide();

    $(".round").corner("8px");
    $(".round-4").corner("4px");
    $("a.button").corner("4px");

    $('*[placeholder]').placeholder();
    
    $("#update-form").validate();
    
    $("#update-box #product-text").autocomplete({
        minLength: 1,
        source: "/api/brand/auto-suggest",
        close: function(event, ui) {
            if(ui.item){
                $("#cid").attr("value",ui.item.id);
            }else{
                $("#cid").attr("value","");                
            }
        },
        open: function(event, ui) {
            if(ui.item){
                $("#cid").attr("value",ui.item.id);
            }else{
                $("#cid").attr("value","");                
            }
        },
        select: function(event, ui) {
            if(ui.item){
                $("#cid").attr("value",ui.item.id);
            }else{
                $("#cid").attr("value","");                
            }
        },
        change: function(event, ui) {
            if(ui.item){
                $("#cid").attr("value",ui.item.id);
            }else{
                $("#cid").attr("value","");                
            }
        }
    });

	$(".bubble-button").hover(function(){
		clearInterval(bubbleTimer);
		
		$(".bubbles").hide();
		
		$(this).next().css({
            'position': 'absolute',
            'left': $(this).offset().left - 65 + 'px',
            'top': $(this).offset().top + 20 + 'px',
        }).show();
         
		$(this).next().hover(function(){
			clearInterval(bubbleTimer);
		},function(){
			removeAllBubbles();
		});
		
	},function(){
		 bubbleTimer = setInterval("removeAllBubbles()",3000);
	});

	$("#to-input").autoSuggest("/api/user/auto-suggest", {
            asHtmlID: "to",
            neverSubmit: true,
            startText: "To: Everyone",
            selectedItemProp: "label",
            selectedValuesProp: "value",
            searchObjProps: "name",
            minChars: 2,
            matchCase: false
        });

	$(".activity-text").focus(function(){
        $("#update-box").animate({
            height: "220px"
        }, 400);
		$("#update-box textarea").fadeIn(300);
		$("#update-box #add-image").fadeIn(300);
		$("#update-box #social-tools").fadeIn(300);
    });

    $(".action-selector").hover(function(){
    	$(this).find("#update-box .action-list").filter(':not(:animated)').slideDown(300);
    },function(){
    	$(this).find("#update-box .action-list").slideUp(300);
    });

    $("#update-box .action-list a").click(function(e){
    	$(".selected-action").html($(this).text());
    	$("#aid").attr("value",$(this).attr("aid"));
    	$(".action-list").hide();
    	return false;
    });
    
    try {
        $('#update-form').ajaxForm({
            target: '#output1', 
            beforeSubmit: function(formData, jqForm, options){
                var s = $("#update-box-new #product-text").attr("value");
                if(s == "What brand did you buy?")
                    return false;
                if(s == "What do you want to wish for?")
                    return false;
                if(s == "What are you watching?")
                    return false;
                if(s == "What are you listening to?")
                    return false;
                if(s == "What are you reading?")
                    return false;
            },
            success: function(responseText, statusText, xhr, $form){
                $("#update-box-new > h2").hide();
                $(".update-container").hide();    
                $("#points-container").show();   
                $("#user-badge .points").attr("p", parseInt($("#user-badge .points").attr("p")) + 2);   
                $("#user-bubble .points").attr("p", parseInt($("#user-bubble .points").attr("p")) + 2);
                   
                $("#user-badge .points").html($("#user-badge .points").attr("p") + "<span> points</span>");
                $("#user-bubble .points").html($("#user-bubble .points").attr("p") + "<span> points</span>");
                
                $.ajax({
                    type:'POST',
                    url:"/home/page/1",
                    data:{"_xsrf":getCookie("_xsrf")},
                    dataType:'html',
                    success:function (data, textStatus) {
                        $("#stream ol").html(data);
                    }
                });
            },
            dataType: 'json',
            clearForm: true,
            resetForm: true
        });
        
        $(".back-button").click(function(e){
            $("#update-box-new > h2").show();
            $(".update-container").show();    
            $("#points-container").hide();   
            e.preventDefault();
        });
    }
    catch (err) {
    }
    
    $(".action-button").click(function(e){
        var s = $(".selected");
        s.removeClass("selected");
        $("#aid").attr("value",$(this).attr("aid"));
        switch($(this).attr("aid")){
            case '1':
                $(this).removeClass("bought-button").addClass("bought-button-selected selected");
                $("#update-box-new #product-text").attr("value","What brand did you buy?");
                $("#update-box-new #product-text").attr("placeholder","What brand did you buy?");
                break;
            case '2':
                $(this).removeClass("wish-button").addClass("wish-button-selected selected");
                $("#update-box-new #product-text").attr("value","What do you want to wish for?");
                $("#update-box-new #product-text").attr("placeholder","What do you want to wish for?");
                break;
            case '3':
                $(this).removeClass("watching-button").addClass("watching-button-selected selected");
                $("#update-box-new #product-text").attr("value","What are you watching?");
                $("#update-box-new #product-text").attr("placeholder","What are you watching?");
                break;
            case '4':
                $(this).removeClass("listening-button").addClass("listening-button-selected selected");
                $("#update-box-new #product-text").attr("value","What are you listening to?");
                $("#update-box-new #product-text").attr("placeholder","What are you listening to?");
                break;
            case '5':
                $(this).removeClass("reading-button").addClass("reading-button-selected selected");
                $("#update-box-new #product-text").attr("value","What are you reading?");
                $("#update-box-new #product-text").attr("placeholder","What are you reading?");
                break;
        } 
        
        switch($(s).attr("aid")){
            case '1':
                $(s).removeClass("bought-button-selected").addClass("bought-button"); 
                break;
            case '2':
                $(s).removeClass("wish-button-selected").addClass("wish-button"); 
                break;
            case '3':
                $(s).removeClass("watching-button-selected").addClass("watching-button"); 
                break;
            case '4':
                $(s).removeClass("listening-button-selected").addClass("listening-button"); 
                break;
            case '5':
                $(s).removeClass("reading-button-selected").addClass("reading-button"); 
                break;
        } 
        e.preventDefault();
    });

    $(".twitter-login").click(function(e){
        var left = (screen.width / 2) - (780 / 2);
        var top = (screen.height / 2) - (420 / 2);
        mywindow = window.open('/connect/twitter/login', 'twitterlogin', 'location=0,status=0,scrollbars=0,width=780,height=440,' + 'top=' + top + ',left=' + left);
        e.preventDefault();
    });

    $(".facebook-login").click(function(e){
        var left = (screen.width / 2) - (990 / 2);
        var top = (screen.height / 2) - (560 / 2);
        mywindow = window.open('/connect/facebook/login', 'twitterlogin', 'location=0,status=0,scrollbars=0,width=990,height=560,' + 'top=' + top + ',left=' + left);
        e.preventDefault();
    });
    
    $(".icon,.text").click(function(e){
        $(".text").remove();    
        $(".icon").unbind("click");    
        $(".file-container").show();
        $(".file-container input[type='file']").filestyle({
              image: "/static/images/browse-button.png",
              imageheight : 27,
              imagewidth : 74,
              width : 150
        });
        return false;
    });
    
    $(".drop-down-button").toggle(function() {
          $(".drop-down-content").slideDown(300);
    }, function() {
          $(".drop-down-content").slideUp(300);
    });
    
    $(".create-brand-button").click(function(e){
        $('<div style="display:none;overflow:hidden;" title=""></div>').addClass("create-brand-dialog dialog").appendTo('body');
        $(".create-brand-dialog").load(
            $(this).attr("href"), 
            null,
            function (responseText, textStatus, XMLHttpRequest) {
                $(".create-brand-dialog").dialog({
                    title:"Create a brand",
                    modal: true,
                    draggable: false,
                    resizable: false,
                    width: 620,
                    height: 560,
                    open: function(event, ui){
                          formvalidation();
                    },
                    close: function(event, ui){
                        $(".tipsy").hide();
                        $(".create-brand-dialog").remove();
                    },
                    buttons:{
                        "Create Brand": function(){
                            $('#brand-form').submit();
                        },
                        "Cancel": function(){
                            $( this ).dialog( "close" );
                        }
                    }
                });
            }
        );

        return false;
    });
    
    $(".edit-brand-button").click(function(e){
        $('<div style="display:none;overflow:hidden;" title=""></div>').addClass("edit-brand-dialog dialog").appendTo('body');
        $(".edit-brand-dialog").load(
            $(this).attr("href"), 
            null,
            function (responseText, textStatus, XMLHttpRequest) {
                $(".edit-brand-dialog").dialog({
                    title:"Edit brand",
                    modal: true,
                    draggable: false,
                    resizable: false,
                    width: 620,
                    height: 510,
                    close: function(event, ui){
                        $(".tipsy").hide();
                        $(".edit-brand-dialog").remove();
                    },
                    buttons:{
                        "Save": function(){
                            $('#brand-form').submit();
                        },
                        "Cancel": function(){
                            $( this ).dialog( "close" );
                        }
                    }
                });
            }
        );

        return false;
    });
    
    $(".create-deal-button").click(function(e){
        $('<div style="display:none;overflow:hidden;" title=""></div>').addClass("create-deal-dialog dialog").appendTo('body');
        $(".create-deal-dialog").load(
            $(this).attr("href"), 
            null,
            function (responseText, textStatus, XMLHttpRequest) {
                $(".create-deal-dialog").dialog({
                    title:"Create a Deal",
                    modal: true,
                    draggable: false,
                    resizable: false,
                    width: 620,
                    height: 450,
                    close: function(event, ui){
                        $(".tipsy").hide();
                        $(".create-deal-dialog").remove();
                    }
                });
            }
        );

        return false;
    });
    
    $(".edit-deal-button").click(function(e){
        $('<div style="display:none;overflow:hidden;" title=""></div>').addClass("edit-deal-dialog dialog").appendTo('body');
        $(".edit-deal-dialog").load(
            $(this).attr("href"), 
            null,
            function (responseText, textStatus, XMLHttpRequest) {
                $(".edit-deal-dialog").dialog({
                    title:"Edit Deal",
                    modal: true,
                    draggable: false,
                    resizable: false,
                    width: 620,
                    height: 450,
                    close: function(event, ui){
                        $(".tipsy").hide();
                        $(".create-deal-dialog").remove();
                    }
                });
            }
        );

        return false;
    });
    
    [
    {
    	"key":"value",
    	"key":"value",
    	"key":"value",
    	"key":"value",
    	"key":"value",
    	"phone":["12121","454132132"],
    },
    {
    	"key":"value",
    	"key":"value",
    	"key":"value",
    	"key":"value",
    	"key":"value",
    	"phone":["12121","454132132"],
    }
    ]
    
     $("#qrcode-dialog").dialog({
        modal: true,
        autoOpen: false,
        draggable: false,
        resizable: false,
        width: 600,
        height: 400,
    });
    
    $("#qrcode-button") .click(function(e) {
    	$("#qrcode-dialog").dialog('open');
        e.preventDefault();
    });
    
    $('#preview-image').attr("src","http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=L|0&chl="+$("#link-string").attr("href"));
    $('#download-button').attr("href","http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=L|0&chl="+$("#link-string").attr("href"));
    
	$('#preview-image').attr({width:300,height:300});
	
	$('#width') .keyup(function(){
		if (IsNumeric($(this).attr("value"))){
			if (($(this).attr("value")>=50) && ($(this).attr("value")<=500)){
				if ($(this).attr("value")<=300){
					$('#preview-image').attr({width:$(this).attr("value"),height:$(this).attr("value")});
				}else{
					$('#preview-image').attr({width:300,height:300});
				}
				$('#height').attr("value",$(this).attr("value"));
				$('#download-button').attr("href","http://chart.apis.google.com/chart?cht=qr&chs="+$(this).attr("value")+"x"+$(this).attr("value")+"&chld=L|0&chl="+$("#link-string").attr("href"));
				$('#preview-image').attr("src","http://chart.apis.google.com/chart?cht=qr&chs="+$(this).attr("value")+"x"+$(this).attr("value")+"&chld=L|0&chl="+$("#link-string").attr("href"));
			}
		}
	});	
	
	$('#dimension') .change(function() {
		if ($(this).val() != 0) {
			$('#download-button').attr("href","http://chart.apis.google.com/chart?cht=qr&chs="+$(this).val()+"x"+$(this).val()+"&chld=L|0&chl="+$("#link-string").attr("href"));
			$('#preview-image').attr("src","http://chart.apis.google.com/chart?cht=qr&chs="+$(this).val()+"x"+$(this).val()+"&chld=L|0&chl="+$("#link-string").attr("href"));	
			$('#width').attr("value",$(this).val());
			$('#height').attr("value",$(this).val());
			$('#preview-image').attr({width:$(this).val(),height:$(this).val()});
			$("#custom-dimensions").hide();
		}else{
			$("#custom-dimensions").show();
		}
	});
    
    formvalidation();
    sethookcontrols();
    
	notifierSetup();
	generateToolTips();
	social_buttons();
});


function IsNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

function init_buzzar_media(){
     $(".buzzar_media_item").click(function(e){
       $(this).parent().flash(
            {
                swf: '/static/swfs/BuzzarVideoPlayer.swf',
                width: 580,
                height: 326,
                bgcolor: 0x000000,
                allowScriptAccess: "always",
                allowFullScreen: true,
                flashvars: {
                    v: $(this).attr('href')
                }
            }
        );
       $(this).remove();
       return false; 
    });
    
    $(".youtubify").click(function(e){
       $(this).parent().flash(
            {
                swf: 'http://youtube.com/v/'+$(this).attr('href')+'?version=3&color1=0x000000&color2=0x333333&feature=player_embedded&hl=en_US&fs=1&rel=0',
                width: 580,
                height: 326,
                bgcolor: 0x000000,
                allowScriptAccess: "always",
                allowFullScreen: true,
                flashvars: {
                    v: $(this).attr('href')
                }
            }
        );
       $(this).remove();
       return false; 
    });
    
    $(".vimeoify").click(function(e){
       $(this).parent().flash(
            {
                swf: 'http://vimeo.com/moogaloop.swf?clip_id='+$(this).attr('href')+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=8a8a8a&amp;fullscreen=1',
                width: 580,
                height: 326,
                bgcolor: 0x000000,
                allowScriptAccess: "always",
                allowFullScreen: true,
                flashvars: {
                    v: $(this).attr('href')
                }
            }
        );
       $(this).remove();
       return false; 
    });
}

var h= "";

function sethookcontrols(){
     $("a.image_lightbox").fancybox({
            'titleShow': false,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'centerOnScroll': false
        });
        
    $(".delete-button").unbind('click');
    $(".delete-button").click(function(e){
        var answer = confirm("Are you sure to delete this item?");
        h = "";
        if (answer){
            h = $(this).attr("name");
            $.ajax({
                type: "POST",
                url: $(this).attr("href") + "&_xsrf=" + getCookie("_xsrf"),
                data: "",
                dataType: "json",
                success: function(data, textStatus){
                    notify(data['status'],data['message']);
                    $("#item-"+h).parent().remove(); 
                    h = "";
                }
            });
        }
        answer = null;
        e.preventDefault();
    }); 
    
    $(".like-icon").unbind('click');
    $(".like-icon").click(function(e){
        h = "";
        h = $(this).attr("name");
        $.ajax({
            type: "POST",
            url: $(this).attr("href") + "&_xsrf=" + getCookie("_xsrf"),
            data: "",
            dataType: "json",
            success: function(data, textStatus){
                if(data['status'] == 0){                
                    notify(data['status'],data['message']);
                }else{
                    $("#like-image-"+h).attr("src",data['result'])
                    notify(data['status'],"Liked!");
                }
                 
            }
        });
        e.preventDefault();
    });
}

function init_likes(){
    $(".like-popup").hide();

    likepopup();

    $(".like-popup").hover(function(){
        like_popup_flag = false;
    }, function(){
        like_popup_flag = true;
        $(".like-popup").fadeOut(500);
    });
}

var like_popup_timer;
var like_popup_flag = true;

function likepopup(){
    $('.like').hover(function(){
        like_popup_flag = true;
        $(".like-popup").hide();
        $(this).next().css({
            'position': 'absolute',
            'left': $(this).offset().left - 103 + 'px',
            'top': $(this).offset().top - 80 + 'px'
        }).fadeIn(300);
    }, function(){
        like_popup_flag = true;
        like_popup_timer = setTimeout("hidelikepopup()", 3000);
    });
}

function hidelikepopup(){
    if (like_popup_flag) {
        $(".like-popup").fadeOut(300);
        clearTimeout(like_popup_timer);
    }
    else {
        clearTimeout(like_popup_timer);
    }
}

function generateToolTips(){
	$('*[tooltip]').tipsy({
		title: 'tooltip',
		gravity: 's',
		opacity: 1
	});
}

function removeAllBubbles(){
	$(".bubbles").fadeOut(500);
}

function moreButtons(){
	$(".more-button").click(function(e){
		$(this).text("Loading...");
		$.ajax({
				type:'POST',
				url:$(this).attr("href"),
				data:{"_xsrf":getCookie("_xsrf")},
				dataType:'html',
				success:function (data, textStatus) {
					$(".more-button").hide();
					$(".more-button").before(data);
					$(".more-button:hidden").remove();
				}
			});
		return false;
	});
}

function social_buttons(){
    $(".follow-button, .unfollow-button").click(function(e){
       $.ajax({
            type:'POST',
            url:$(this).attr("href"),
            data:{"_xsrf":getCookie("_xsrf")},
            dataType:'html',
            success:function (data, textStatus) {
                if(data["status"]==0){
                    notify(0, data["message"]);
                }else{
                    //notify(1, data["message"]);
                    window.location.reload()
                }
            }
        });
       e.preventDefault(); 
    });
}

function notifierSetup(){
	window.notify = function(type, message){
		var title = "";
		var icon = "ui-icon ui-icon-info";

		if (type == 0) {
			title = "Error!";
			icon = "ui-icon ui-icon-alert";
		}
		else if (type == 1) {
			title = "Success!";
			icon = "ui-icon ui-icon-check";
		}
		else if (type == 2) {
			title = "Done!";
			icon = "ui-icon ui-icon-lightbulb";
		}
		else if (type == 3) {
			title = "Alert!";
			icon = "ui-icon ui-icon-alert";
		}

		$.pnotify({
			pnotify_history: false,
			pnotify_nonblock: false,
			pnotify_notice_icon: icon,
			pnotify_title: title,
			pnotify_text: message
		});
	};
}

function getCookie(name){
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}

function formvalidation(){
    $.validator.setDefaults({
        success: "input-success",
        validClass: "input-success",
        errorPlacement: function(error, element){
            $(element).attr('original-title', error.text());
            if($(element).attr("type") == "file"){
                $(element).tipsy({
                    trigger: 'manual',
                    gravity: 'w',
                    offset: 70,
                    opacity: 1
                });    
            }else{
                $(element).tipsy({
                    trigger: 'manual',
                    gravity: 'w',
                    opacity: 1
                });
            }
            
            $(element).tipsy('show');
        },
        highlight: function(element, errorClass, validClass){
            $(element).removeClass("input-invalid");
            $(element).removeClass("input-success");
            $(element).addClass("input-invalid");
            $(element).tipsy('show');
        },
        unhighlight: function(element, errorClass, validClass){
            $(element).attr('original-title', '');
            $(element).tipsy('hide');
            $(element).removeClass("input-invalid");
            $(element).removeClass("input-success");
        }
    });

    $("form input").tipsy({
        trigger: 'manual',
        gravity: 'w',
        opacity: 1
    });
}

