/* $Id: scripts.js 11888 2011-05-27 12:54:39Z markon $ */

/*
	Featured carousel
*/
function mycarousel_initCallback(carousel) {
    $('#featured_paging a').bind('click', function() {
        carousel.scroll($.jcarousel.intval($(this).text()));

		$('#featured_paging a').removeClass('active');
		$(this).addClass('active');
		
        return false;
    });
};

function paging_selected(a,b,step,d) {
	$('#featured_paging a').removeClass('active');
	$('#featured_paging a:eq(' + (step-1) + ')').addClass('active');
}
/*
	Sidebar Image Switcher
*/
function swapImages(){
	var $active = $('#s_contest .active');
	var $next = ($('#s_contest .active').next().length > 0) ? $('#s_contest .active').next() : $('#s_contest a:first');
	$active.fadeOut(function(){
		$active.removeClass('active');
		$next.fadeIn().addClass('active');
	});
}

//sidebar widget
function setClearInterval(focused_window){
	if (focused_window == false) {
		setInterval("slideSwitch()",30000);
	} else {
		clearInterval();
	}
}
//slideshow of tabs for sidebar widget
function slideSwitch() {
    var $active = $('#s_sidebar_widget .container.active');
	var $menu_active = $('#s_sidebar_widget ul li.active');

    if ( $active.length == 0 ) $active = $('#s_sidebar_widget .container:last');
    if ( $menu_active.length == 0 ) $menu_active = $('#s_sidebar_widget ul li:last');

    var $next =  $active.next().length ? $active.next()
        : $('#s_sidebar_widget .container:first');
	var $menu_next = $menu_active.next().length ? $menu_active.next()
		: $('#s_sidebar_widget ul li:first');

    $active.addClass('last-active');
	$menu_active.addClass('last-active');

    $next.addClass('active');
	$menu_next.addClass('active');
    $active.removeClass('active last-active');
	$menu_active.removeClass('active last-active');
}

var response = true;

function createplayer(theFile, go, id) {
	var so = new SWFObject('/plugins/flv_player/player.swf','mpl','320','240','9');
	so.addParam('allowscriptaccess','always');
	//so.addVariable("file",theFile);
	so.addParam('allowfullscreen','true');
	so.addParam('stretching','none');
	so.addParam('wmode','transparent');
	so.addParam('skin','/plugins/flv_player/skins/modieus.swf');
    //so.addParam('flashvars','skin=/plugins/flv_player/skins/modieus.swf');
    so.addParam('flashvars','file='+ theFile +'&autostart=true&skin=/plugins/flv_player/skins/modieus.swf');
    
	if (go) {so.addVariable("autostart","true");}
	so.write('player' + id);
	//console.log(theFile);
}

function createaudioplayer(theFile, go, id) {
	var so = new SWFObject('/plugins/flv_player/player.swf','mpl','282','20','9');
	so.addParam('allowscriptaccess','always');
	so.addParam('allowfullscreen','false');
	so.addParam('stretching','none');
	so.addParam('wmode','transparent');
    so.addParam('flashvars','file='+ theFile +'&autostart=true');
    
	if (go) {so.addVariable("autostart","true");}
	so.write('player' + id);
	//console.log(theFile);
}

function createaudioplayerbig(theFile, go, id) {
	var so = new SWFObject('/plugins/flv_player/player.swf','mpl','630','20','9');
	so.addParam('allowscriptaccess','always');
	so.addParam('allowfullscreen','false');
	so.addParam('stretching','none');
	so.addParam('wmode','transparent');
    so.addParam('flashvars','file='+ theFile +'&autostart=true');
    
	if (go) {so.addVariable("autostart","true");}
	so.write('player' + id);
	//console.log(theFile);
}


/*
	Jquery popup window
*/

$.fn.popupWindow = function(instanceSettings){
		
	return this.each(function(){
	
	$(this).click(function(){
	
	$.fn.popupWindow.defaultSettings = {
		centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
		centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
		height:500, // sets the height in pixels of the window.
		left:0, // left position when the window appears.
		location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
		menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
		resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
		scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
		status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
		width:500, // sets the width in pixels of the window.
		windowName:null, // name of window set from the name attribute of the element that invokes the click
		windowURL:null, // url used for the popup
		top:0, // top position when the window appears.
		toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
	};
	
	settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});
	
	var windowFeatures =    'height=' + settings.height +
							',width=' + settings.width +
							',toolbar=' + settings.toolbar +
							',scrollbars=' + settings.scrollbars +
							',status=' + settings.status + 
							',resizable=' + settings.resizable +
							',location=' + settings.location +
							',menuBar=' + settings.menubar;

			settings.windowName = this.name || settings.windowName;
			settings.windowURL = this.href || settings.windowURL;
			var centeredY,centeredX;
		
			if(settings.centerBrowser){
					
				if ($.browser.msie) {//hacked together for IE browsers
					centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
					centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
				}else{
					centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
					centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
				}
				window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
			}else if(settings.centerScreen){
				centeredY = (screen.height - settings.height)/2;
				centeredX = (screen.width - settings.width)/2;
				window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
			}else{
				window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();	
			}
			return false;
		});
	});	
};

/*
	SMS character counter
*/
function counter(){
    var message = $('#message').val();
    var limit = 160;
    
    if(message.length > limit){
        message = message.substring(0, limit);
        $('#message').val(message);
    }
    
    $('#charcount').html(limit - message.length);
}

$(function() {

    var addClickHandlers = function() {
		/*
			Registration
		*/
       
		//validate password
		$('#registration input.password').blur(function(){
			if ($(this).val() == '') {
				$('#registration input.password').parent('.item').addClass('error');
				$('#registration input.password').next('.error_info').show();
			} else {
				$('#registration input.password').parent('.item').removeClass('error');
				$('#registration input.password').next('.error_info').hide();
			}
		});
		
		//validate nickname on blur
		$('#registration input.nickname').blur(function() {
			$.post('/register/verify-nickname', {nickname: $(this).val()}, function(data) {
				if (data.success) {
					$('#registration input.nickname').parent('.item').removeClass('error');
					$('#registration input.nickname').next('.error_info').remove();
				} else {
					$('#registration input.nickname').parent('.item').addClass('error');
	
					if ($('#registration input.nickname').next('.error_info').length == 0)
						$('#registration input.nickname').after('<div class="error_info">' + data.msg + '</div>');
				}
			}, 'json');
		});
		
		//validate operator on change
		$('#registration select.operator').change(function(){
			$.post('/register/verify-operator', {operator: $(this).val()}, function(data) {
				if (data.success) {
					$('#registration select.operator').parentsUntil('.item').parent().removeClass('error');
					$('#registration select.operator').next('.error_info').remove();
				} else {
					$('#registration select.operator').parentsUntil('.item').parent().addClass('error');
		
					if ($('#registration select.operator').next('.error_info').length == 0)
						$('#registration select.operator').after('<div class="error_info">' + data.msg + '</div>');
					}
			}, 'json');
		});
		
		//validate email
		$('#registration input.email').blur(function() {
			$.post('/register/verify-email', {email: $(this).val()}, function(data) {
				if (data.success) {
					$('#registration input.email').parent('.item').removeClass('error');
					$('#registration input.email').next('.error_info').remove();
				} else {
					$('#registration input.email').parent('.item').addClass('error');
	
					if ($('#registration input.email').next('.error_info').length == 0)
						$('#registration input.email').after('<div class="error_info">' + data.msg + '</div>');
				}
			}, 'json');
		});
		
		//validate phone number
		$('#registration input.msisdn').blur(function() {
			$.post('/register/verify-msisdn', {msisdn: $(this).val()}, function(data) {
				if (data.success) {
					$('#registration input.msisdn').parent('.item').removeClass('error');
					$('#registration input.msisdn').next('.error_info').remove();
				} else {
					$('#registration input.msisdn').parent('.item').addClass('error');
	
					if ($('#registration input.msisdn').next('.error_info').length == 0)
						$('#registration input.msisdn').after('<div class="error_info">' + data.msg + '</div>');
				}
			}, 'json');
		});
		
		//validate phone number and operator and send pin
		$('#registration a.send_pin').click(function() {
			$.post('/register/send-pin', {msisdn: $("#registration input#msisdn").val(), operator: $('#registration select.operator').val(), full_access: $('#registration select#full_access').val()}, function(data) {
				if (data.success) {
					$('#registration select.operator').parent('.item').removeClass('error');
					$('#registration select.operator').next('.error_info').remove();

					$('#registration input.msisdn').parent('.item').removeClass('error');
					$('#registration input.msisdn').next('.error_info').remove();

                    $('#registration #pin-notice').html(data.msg);
                    $('#registration #pin-notice').show();

                    $('#registration select#full_access').attr("disabled", "disabled");
                    var full_access = $('#registration select#full_access').val();
                    $('#registration-form').append('<input type="hidden" name="full_access" value="' + full_access + '" />');
				} else {
					if (data.type == 'msisdn') {
						$('#registration input.msisdn').parent('.item').addClass('error');
		
						if ($('#registration input.msisdn').next('.error_info').length == 0) {
                            $('#registration input.msisdn').after('<div class="error_info">' + data.msg + '</div>');
                        }
					} else {
                        $('#registration select.operator').parentsUntil('.item').parent().addClass('error');

                        if ($('#registration select.operator').next('.error_info').length == 0) {
                            $('#registration select.operator').after('<div class="error_info">' + data.msg + '</div>');
                        }
//						$('#registration select.operator').parent('.item').addClass('error');
//
//						if ($('#registration select.operator').next('.error_info').length == 0)
//							$('#registration select.operator').after('<div class="error_info">' + data.msg + '</div>');
					}
				}
			}, 'json');
            return false;
			
			return false;
		});

        //
        $('.ui-autocomplete-input').css('width','300px')
        
		if ($("#registration .referrer").length != 0) {
			$("#registration .referrer").autocomplete({
            	source: "/register/profiles",
            	minLength: 2,
            	select: function(event, ui) {
            	    $("#referrer").val(ui.item.label);
            	    $("#referrer_pid").val(ui.item.id);
            	    return false;
            	}
        	});
		}
		
		//validate pin
        /*
		$('#registration input.pin').blur(function() {
			$.post('/register/verify-pin', { pin: $(this).val(), msisdn: $('#registration input.msisdn').val(), operator: $('#registration select.operator').val() }, function(data) {
				if (data.success) {
					$('#registration input.pin').parent('.item').removeClass('error');
					$('#registration input.pin').next('.error_info').remove();
				} else {
					$('#registration input.pin').parent('.item').addClass('error');
	
					if ($('#registration input.pin').next('.error_info').length == 0)
						$('#registration input.pin').after('<div class="error_info">' + data.msg + '</div>');
				}
			}, 'json');
		});
        */

        $('#registration-form').submit(function() {
	        if ($('#registration .item.error').length == 0) {
				$(this).ajaxSubmit({
            	    success: function(data) {
            	        
            	        if (data.success == true) {
            	            window.location = "/home/tab/wall";
            	        } else {
            	            alert(data.msg);
            	        }
            	        return false;
            	    },
            	    dataType: 'json'
            	});
			}
            return false;
        });

		//tooltip
		$('#registration a.help').hover(function() {
			$(this).children().show();
		},function() {
			$(this).children().hide();
		})
		/*
			Execute Sidebar Image Switcher
		*/
		setInterval('swapImages()', 5000);
		/*
			playlist hovers
		*/
		$('div.playlist-container a').hover(function(){
			$(this).children('span').show();
		},function(){
			$(this).children('span').hide();
		});
		/*
			playlist currently playing
		*/
		$('div.playlist-container a').click(function(){
			$('#currently_playing').html($(this).attr('title'));
		});
		/*
			playlist open in popup
		*/
		$('.popup_player').popupWindow({ 
			centerBrowser: 1,
			width: 300,
			height: 278
		});
		$('.popup_player_playlist').popupWindow({ 
			centerBrowser: 1,
			width: 300,
			height: 278
		});
		
		//fixed banner-------------------------------------------------------------------------
		if (!$('#ad_160x600')) {
			var msie6 = $.browser == 'msie' && $.browser.version < 7;
	  
			if (!msie6) {
				var top = $('#ad_160x600').offset().top - parseFloat($('#ad_160x600').css('margin-top').replace(/auto/, 0));
				$(window).scroll(function (event) {
					// what the y position of the scroll is
					var y = $(this).scrollTop();
					
					// whether that's below the form
					if (y >= top) {
						// if so, ad the fixed class
						$('#ad_160x600 div').addClass('fixed');
					} else {
						// otherwise remove it
						$('#ad_160x600 div').removeClass('fixed');
					}
				});
			}  
		}
		
		//freesms widget on first page --------------------------------------------------------
		$('#freesms_widget').click(function(){
			$("#widget-container").load("/sms-widget");
		});
		
        //close forms -------------------------------------------------------------------------
        $(".link_close").click(function() {
            $("div#forms").hide();
            $("div#forms").html("");
            $("div#forms").addClass("loader");
            $("div#forms_upload").hide();
            $("div#forms").html("");
            $("div#forms").addClass("loader");
        });
        $(".link_hide").click(function() {
            $("div#forms").hide();
        });

        //handle IMAGE rotating ---------------------------------------------------------------
        $(".link_rotate_right, .link_rotate_left").click(function() {
            $("div#forms").html("");
            $("div#forms").addClass("loader");
            $("div#forms").load(this.href, function() {
                $("div#forms").removeClass("loader");
                $("div#forms").css("background-color","#bde1ea");
                $("div#forms").animate({backgroundColor: "#ffffff"}, 1000);
                addClickHandlers();
            });
            return false;
        });

        //handle ugc UPLOAD -------------------------------------------------------------------
        $(".link_add_picture_video").click(function() {
            $("div#forms").hide();
            $("div#forms_upload").css("background-color","#bde1ea");
            $("div#forms_upload").show();
            $("div#forms_upload").animate({backgroundColor: "#ffffff"}, 1000);
            return false;
        });

        //INBOX
        //reply -------------------------------------------------------------------------------
        $("#inbox_expanded a.link_reply").click(function() {
            $(".reply").slideDown('fast');
            return false;
        });

        //close -------------------------------------------------------------------------------
        $("#inbox_expanded a.link_close").click(function() {
            //show all hidden items
            $("#inbox > .item").show();
            //..and close this one
            $("#inbox_expanded").remove();
            $(".reply").show();
            return false;
        });

        //accept friend request -------------------------------------------------------------------------------
        $("#inbox_expanded").children("div.friend_request").children(".content").children(".link_accept", this).click(function() {
            $("#inbox_expanded").load(this.href, addClickHandlers);
            return false;
        });

        //voting - hot or not---------------------------------------------------------------------------------
        $(".thumb_up, .thumb_down").click(function(){
            $("#hot_or_not").load(this.href, addClickHandlers);
            return false;
        });

        $('textarea').autogrow({lineHeight:14,paddingLeft:7,paddingRight:7,paddingTop:3,paddingBottom:3});

        //show password field if selected -----------------------------------------------------
        $("#privacy").bind("change",function(){
            if ($("#privacy").val() == "password") {
                $("#privacy_password").slideDown("fast");
            } else {
                $("#privacy_password").slideUp("fast");
            }
        });

        //new message toggle input fields
        $("div#i_choose input").change(function() {
            if ($(this).val() == "nickname") {
                $("#i_msisdn").hide();
                $("#i_nickname").show();
            } else {
                $("#i_nickname").hide();
                $("#i_msisdn").show();
            }
        });

        //submit a form to delete message in inbox
        $("form div.content > a.link_delete").click(function() {
            //set new form action and submit it
            $("form#inbox_form").attr("action", "/deleteinboxitems");
            $("form#inbox_form").submit('submit');
        });

        //embed for home / gallery
        $("input#image_embed").val("[img]" + $("#selected_image").attr("src") + "[/img]");
        $("input#image_embed, input#image_link").focus(function() {
            this.select();
        });
    }
    addClickHandlers();

    //open new message form----------------------------------------------------------------
    $("a.link_new_message").click(function() {
        $("div#forms").show();
        $("div#forms").load("/getnewmessage", function() {
            $("div#forms").removeClass("loader");
            $("div#forms").css("background-color","#bde1ea");
            $("div#forms").animate({backgroundColor: "#ffffff"}, 1000);
            addClickHandlers();
        });
        return false;
    });

    //load ajax ugc -----------------------------------------------------------------------
    $("a.ugc_thumb", this).click(function() {
        //$("div#forms").html("");
        //$("div#forms").addClass("loader");
        $("div#forms_upload").hide();
        $("div#forms").show();
        $("div#forms").load(this.href, function() {
            $("div#forms").removeClass("loader");
            $("div#forms").css("background-color","#bde1ea");
            $("#forms").animate({backgroundColor: "#ffffff"}, 1000);
            //$('a[rel*=facebox]').facebox();
            addClickHandlers();
        });
        return false;
    });

    //load album form fields --------------------------------------------------------------

    $("#albums a.edit, .link_add_album", this).click(function() {
        $("div#forms").show();
        $("div#forms").load(this.href, function() {
            $("div#forms").removeClass("loader");
            $("div#forms").css("background-color","#bde1ea");
            $("div#forms").animate({backgroundColor: "#ffffff"}, 1000);
            addClickHandlers();
        });
        return false;
    });
	
	//load music form fields
	
    $("#playlist a.edit-song", this).click(function() {
        $("div#forms").show();
        $("div#forms").load(this.href, function() {
            $("div#forms").removeClass("loader");
            $("div#forms").css("background-color","#bde1ea");
            $("div#forms").animate({backgroundColor: "#ffffff"}, 1000);
            addClickHandlers();
        });
        return false;
    });


    //INBOX -------------------------------------------------------------------------------
    //select all checkboxes
    $('#all').click(function(){
        if ($('#all').attr('checked')) {
            $('.msg_cb').attr('checked','checked');
        } else {
            $('.msg_cb').attr('checked','');
        }
    });

    //submit a form
    $("#inbox_delete, #inbox_markread").click(function() {
        //set new form action and submit it
        $("form#inbox_form").attr("action", this.href);
        $("form#inbox_form").submit();
        return false;
    });

    //shift select plugin
    $.fn.enableCheckboxRangeSelection = function() {
        var lastCheckbox = null;
        var $spec = this;
        $spec.bind("click", function(e) {
            if (lastCheckbox != null && e.shiftKey) {
                $spec.slice(
                Math.min($spec.index(lastCheckbox), $spec.index(e.target)),
                Math.max($spec.index(lastCheckbox), $spec.index(e.target)) + 1
                ).attr({checked: e.target.checked ? "checked" : ""});
            }
            lastCheckbox = e.target;
        });
        return $spec;
    };
    $("input.msg_cb").enableCheckboxRangeSelection();

    var test = false;
    //click on div
    $("div#inbox > div.item", this).click(function() {
        if(!test) {
            ref = $(this);
            //get type and id from element's id
            pos     = this.id.indexOf('-');
            type    = this.id.substring(0,pos);
            id      = this.id.substring(pos + 1);
            //console.log($(this));
            //setloader icon to this item
			//console.log(ref);
			ref.find('span.itemico').hide();
            ref.addClass('loader');
            //remove all previously expanded items
            $("#inbox_expanded").remove();
            //show all hidden items
            $("#inbox > .item").show();
            //remove loader class to all other items

            ref.removeClass("new");
            if ($(this).attr('class').split(' ').slice(-2) == 'first,loader') {
                $(ref).after('<div id="inbox_expanded" class="first"></div>');
            } else {
                $(ref).after('<div id="inbox_expanded"></div>');
            } 
 			$("#inbox_expanded").load("/inboxitem/type/" + type + "/id/" + id, function() {
                $(ref).hide();
                ref.removeClass('loader');
				$('#inbox_expanded').addClass('border');
				ref.find('span.itemico').show();
                addClickHandlers();
            });
        } else {
            test = false;
        }
    });

    //click on checkbox
    $("input.msg_cb", this).click(function() {
        test = true;
    });

    //close error and success messages ---------------------------------------------------
    $('#error_close').click(function(){
        $('#error').hide();
    });
    $('#success_close').click(function(){
        $('#success').hide();
    });

    //toggle user info --------------------------------------------------------------------

    $('#show_user_info').click(function(){
        $('#s_user_info ul li').removeClass('hidden');
        $('#show_user_info').hide();
        $('#hide_user_info').show();
        return false;
    });

    $('#hide_user_info').click(function(){
        $("#s_user_info .additional").addClass('hidden');
        $('#hide_user_info').hide();
        $('#show_user_info').show();
        return false;
    });

    //send lost password ------------------------------------------------------------
    $('.link_lost_pass').click(function(){
        $('#login').hide();
        $('#lost_pass').show();
        return false;
    });
	
	$('.lost-pass-cancel').click(function(){
        $('#lost_pass').hide();
        $('#login').show();
        return false;
	});

	//commenting on wall--------------------------------------------------------------
	$('a.add-comment').click(function(){
		if ($(this).siblings('ul.comments').children('.wall_comment_form').css('display') == 'none') {
			if ($(this).siblings('ul.comments').attr('rel') == 'empty') {
				$(this).siblings('ul.comments').show();
			}
			$(this).siblings('ul.comments').children('.wall_comment_form').show();
		} else {
			if ($(this).siblings('ul.comments').attr('rel') == 'empty') {
				$(this).siblings('ul.comments').hide();
			}
			$(this).siblings('ul.comments').children('.wall_comment_form').hide();
		}
		return false;
	});
    //show all comments (delegate)
	$('div#wall div.day ul li ul.comments').click(function(e){
        var target = e.target;
        if ($(target).hasClass('show_all')) {
            currForm = $(this).children('li form.wall-comment-form');
            currCommentsHolder = $(this);
            currComments = currCommentsHolder.children('li.wcremove');
            $.get('/get-wall-comments/wall_id/' + $(target).attr('rel'), function(data) {
                currComments.remove();
                currForm.children('textarea#comment').val('');
                currCommentsHolder.prepend(data);
            });
        }
		return false;
	});
	//post new comment
    $('input#wall-comment-post').click(function() {
        //get parent form
        currForm = $(this).parent('form.wall-comment-form');
        currCommentsHolder = $(this).parents('ul.comments');
        currComments = currCommentsHolder.children('li.wcremove');
        //console.log(currComments);
        currForm.ajaxSubmit({
            type: 'POST',
            url: '/post-wall-comment/',
            success: function(data) {
                currComments.remove();
                currForm.children('textarea#comment').val('');
                currCommentsHolder.prepend(data);
            }
        });
    });

    //clear status and wall comment input -------------------------------------------------
    $("#wall_comment").focus(function(){
        if ($("#wall_comment").val() == $("#wall_comment").attr("title"))
            $("#wall_comment").attr("value", "");
    });

    $("#wall_comment").blur(function(){
        if ($("#wall_comment").val() == "")
            $("#wall_comment").attr("value", $("#wall_comment").attr("title"));
    });

    $("#comment_submit").click(function(){
        if ($("#wall_comment").val() == "" || $("#wall_comment").val() == $("#wall_comment").attr("title")) {
            return false;
        }
    });

    $("#user_status").focus(function(){
        if ($("#user_status").val() == $("#user_status").attr("title"))
            $("#user_status").attr("value", "");
    });

    $("#user_status").blur(function(){
        if ($("#user_status").val() == "")
            $("#user_status").attr("value", $("#user_status").attr("title"));
    });

    $("#status_submit").click(function(){
        if ($("#user_status").val() == "" || $("#user_status").val() == $("#user_status").attr("title")) {
            return false;
        }
    });

    //redirect after category change in public gallery-------------------------
    $("select#choose_category").change(function() {
        //console.log($(this).val());
        //alert("redirect");
        top.location = $(this).val();
    });

    //msisdn for login
    $("#phone_number").focus(function(){
        if ($("#phone_number").val() == $("#phone_number").attr("title"))
            $("#phone_number").attr("value", "");
    });
    $("#phone_number").blur(function(){
        if ($("#phone_number").val() == "")
            $("#phone_number").attr("value", $("#phone_number").attr("title"));
    });

    //validation of empty inputs----------------------------------------------------------------------------
    $("#add_comment_form").submit(function(){
        if ($("#comment").val() == "") {
            $("#add_comment_form > span").append(" (field must not be empty)").css({"color":"#ff0000"});
            return false;
        }
    });

    $("#edit_album_form").submit(function(){
        if ($("#album_title").val() == "") {
            $(".lbl_album_title").append(" (field must not be empty)").css({"color":"#ff0000"});
            return false;
        }
    });

    //send message in sidebar----------------------------------------------------------------------------
    $("#s_main_image .link_send_msg").click(function(){
        $("#s_send_msg").slideDown('fast');
        $("#s_main_image .link_send_msg").css({'font-weight':'bold'});
        return false;
    });

    $("#s_send_msg .link_close_msg").click(function(){
        $("#s_send_msg").slideUp('fast');
        $("#s_main_image .link_send_msg").css({'font-weight':'normal'});
        return false;
    });

    //invite friend in sidebar----------------------------------------------------------------------------
    $("#s_main_image .link_invite_friend").click(function(){
        $("#s_invite_friend").slideDown('fast');
        $("#s_main_image .link_invite_friend").css({'font-weight':'bold'});
        return false;
    });

    $("#s_invite_friend .link_close_msg").click(function(){
        $("#s_invite_friend").slideUp('fast');
        $("#s_main_image .link_invite_friend").css({'font-weight':'normal'});
        return false;
    });

    //add_news
    $("#add_news").click(function() {
        $("div#forms").show();
		return false;
    });


    //profile gallery - AJAX stuff---------------------------------
    //TODO reduce this to only one request and return JSON object
    //on load set embed code

    function addGalleryHandlers() {
        var tmp_link = $("a#link_audio_download").attr('href');
        if (tmp_link) {
            $("a#link_audio_download").attr('href', tmp_link.replace('&',''));
        }
        $("input#image_embed, input#image_link").focus(function() {
            this.select();
        });
        $("input#image_embed").val("[img]" + $("#selected_item img.image").attr("src") + "[/img]");
    }
    addGalleryHandlers();
    
    $("a.pgthumb").click(function() {
		var height = $("#active-item").attr("height");
		if (typeof height == 'undefined') {
			height = 260;
		}
		$('.image_container').css('height',height);
		$('#active-item').hide();
		$('#player').hide();
		$("#image-preloader").css("top",(height/2)-25);
		$("#image-preloader").css("left",260);
        $("#image-preloader").show();
		if (response) {
            response = false;
            url = this.href;
            $.get(url, function(data) {
                $("div#selected_item").html(data);
                $("input#image_embed").val("[img]" + $("#selected_item img.image").attr("src") + "[/img]");
                response = true;
                addGalleryHandlers();
                web2Mobile.rebind();
            });
            $.get("/getugccomments/ugcid/" + $(this).attr("rel"), function(data) {
                $("#comments_container").html(data);
            });
        }
        return false;
    });
	
	//open big picture
	$('.current_image').click(function(){
		window.location($(this).attr('href'));
	});
	
	//add focused class on focus and remove on blur
	//this disables keypress navigation
	$('input').live('focus',function(){
		$(this).addClass('focused');
	});
	$('textarea').live('focus',function(){
		$(this).addClass('focused');
	});
	$('input').live('blur',function(){
		$(this).removeClass('focused');
	});
	$('textarea').live('blur',function(){
		$(this).removeClass('focused');
	});
	
	//call load image on keypress
	$(document).keypress(function(e){
		if ($('input.focused').size() == 0 && $('textarea.focused').size() == 0) {
			var code = (e.keyCode ? e.keyCode : e.which);
			loadImage(code);
		}
	});
	$(document).keydown(function(e){
		if ($('input.focused').size() == 0 && $('textarea.focused').size() == 0) {
			var code = (e.keyCode ? e.keyCode : e.which);
			loadImage(code);
		}
	});
	
	//load image on link click
	$("#selected_item a.next").live('click',function(e){
		loadImage(e.target);
		return false;
	});
	$("#selected_item a.previous").live('click',function(e){
		loadImage(e.target);
		return false;
	});
	
    //gallery (open image) delegate-----------------------------------------------------------------
	function loadImage(e){
        var target = e;
		if (target == 37) {
			id = $('.previous').attr('id');
			if (id == 'link_audio_download') {
				return true;
			}
			url = $('.previous').attr('href');
			url = url.replace('http://' + window.location.hostname,''); //ie6, ie7 hack
			ugcid = $('.previous').attr('rel');
			reload = $('.previous').hasClass('reload');
			next = $('.previous').hasClass('next');
			previous = $('.previous').hasClass('previous');
		} else if (target == 39) {
			id = $('.next').attr('id');
			if (id == 'link_audio_download') {
				return true;
			}
			url = $('.next').attr('href');
			url = url.replace('http://' + window.location.hostname,''); //ie6, ie7 hack
			ugcid = $('.next').attr('rel');
			reload = $('.next').hasClass('reload');
			next = $('.next').hasClass('next');
			previous = $('.next').hasClass('previous');
		} else {
			id = $(target).attr('id');
			if (id == 'link_audio_download') {
				return true;
			}
			url = $(target).attr("href");
            if (url) {
                url = url.replace('http://' + window.location.hostname,''); //ie6, ie7 hack
            }
			ugcid = $(target).attr("rel");
			reload = $(target).hasClass('reload');
			next = $(target).hasClass('next');
			previous = $(target).hasClass('previous');
		}
        //get id of first and last photo
        first   = $("div#gallery div.item > a.first").attr('rel');
        last    = $("div#gallery div.item > a.last").attr('rel');
        //we're on first or last photo - refresh
        if (((last == ugcid) && next) || ((first == ugcid) && previous)) {
			var height = $("#active-item").attr("height");
			if (typeof height == 'undefined') {
				height = 260;
			}
			$('.image_container').css('height',height);
			$('#active-item').hide();
			$('#player').hide();
			$("#image-preloader").css("top",(height/2)-25);
			$("#image-preloader").css("left",260);
			$("#image-preloader").show();
            
            /*
            console.log('first or last');
            //get current url
            var url = document.location.toString();
            if (!url.match('page')) {
                url = url + '/page/1';
            }
            parts = url.split('/');
            url = '';
            var pageIndex;
            var page = 2;
            for (var i in parts) {
                if (parts[i] == "page") {
                    i++;
                    pageIndex = i;//remember index of page
                    page =  parseInt(parts[i]);
                } else if (parts[i] == "ugcid") {
                    //remove ugcid from url
                    parts.splice(parseInt(i),2);
                }
            }
            if (next) page++;
            if (previous && (page > 1)) page--;
            parts[pageIndex] = page;

            url = parts.join('/');
            */
            //console.log(url);
            window.location = url;
            return false;
        }
        if (url && url != "#" && !reload) {
			var height = $("#active-item").attr("height");
			if (typeof height == 'undefined') {
				height = 260;
			}
			$('.image_container').css('height',height);
			$('#active-item').hide();
			$('#player').hide();
			$("#image-preloader").css("top",(height/2)-25);
			$("#image-preloader").css("left",260);
			$("#image-preloader").show();
			
            //console.log("Url:" + url);
            parts = url.split('/');
            found = false;
            jQuery.each(parts, function(i, val) {
                if (val == 'ugcid') {
                    found = i;
                }
            });
            if (found) {
                ugcid = parts[(found+1)];
                if (response && ((parts[1] == 'getprofileugc') || (parts[1] == 'getugc'))) {
                    response = false;
                    $.get(url, function(data) {
                        $("div#selected_item").html(data);
                        response = true;
                    });
                    //also load comments for this image
                    $.get("/getugccomments/ugcid/" + ugcid, function(data) {
                        $("#comments_container").html(data);
                    });
                }
            }

            return false;
        }        
        return true;
    };

    /* facebook connect */
    $("form#form-connect-login").ajaxForm({
        dataType: 'json',
        success: function(data){
            if (data.success != false){
                //redirect to first page
                top.location = '/';
            } else {
                $('#msg-form-1').html(data.msg).show();
				$.fn.colorbox.resize();
				$.fn.colorbox.resize();
            }
        }
    });
    /*
		facebook connect
	*/
    $("form#form-connect-register").ajaxForm({
        dataType: 'json',
        success: function(data){
            if (data.success != false){
                $("input#msisdn2").val(data.msisdn);
                $("input#operator_id2").val(data.operator);
				$.fn.colorbox({inline:true,href:'#fb-register-pin'});
            } else {
                $('#msg-form-2').html(data.msg).show();
				$.fn.colorbox.resize();
				$.fn.colorbox.resize();
            }
        }
    });
    /*
		facebook connect
	*/
    $("form#fb-register-pin-form").ajaxForm({
        dataType: 'json',
        success: function(data){
            if (data.success != false){
                $.fn.colorbox({inline:true,href:'#fb-final-msg'});
            } else {
                $('#msg-form-3').html(data.msg).show();
				$.fn.colorbox.resize();
				$.fn.colorbox.resize();
            }
        }
    });
	/*
		Profile settings tabs
	*/
	$('#settings-tabs li a').click(function(){
		div_id = $(this).attr('rel');
		$('.settings_form').hide();
		$('#settings-tabs li a').removeClass('active');
		$(this).addClass('active');
		$('#' + div_id).show();
		return false;
	});
	/*
		Date picker in settings
	*/
    var d = new Date();
    var year_limit = parseInt(d.getFullYear()) - 12;
	$("#birthdate").datepicker({
		dateFormat: "dd.mm.yy",
		firstDay: 1,
		changeYear: true,
        yearRange: '1900:' + year_limit,
        maxDate: 0
	});
	/*
		Sidebar widget
	*/
	$('#dummy').click(function(){
		$('#dummy').remove();
		$('.container').hide();
		$('#tab-4').show();
		$('#s_sidebar_widget ul li a').css('color','#fff');
		$('#s_sidebar_widget ul li a[rel=tab-4]').css('color','#002e48');
		return false;
	});
	$('#s_sidebar_widget ul li a').click(function(){
		$('.container').hide();
		$('#' + $(this).attr('rel')).show();
		$('#s_sidebar_widget ul li a').css('color','#fff');
		$(this).css('color','#002e48');
		return false;
	});
	setClearInterval(false);
	/*
		Registration
	*/
	$('#send_pin_submit').click(function(){
		$('#send_pin_form').ajaxSubmit({
			url: '/register/sendpin',
			dataType: 'json',
			success: function(data){
				if (data.success != false) {
					$('#send_pin_box').hide();
					$('#enter_pin_box').show();
					$('#msisdn2').val(data.msisdn);
					$('#operator2').val(data.operator);
                    if (data.operator == '11') {
                        $('#enter_pin_box p.instructions').html('Za nastavak upišite PIN. Dobit ćete ga tako, da <strong>pošaljete SMS sa sadržajem PIN na broj 88302</strong>.');
					} else if (data.operator == '12') {
                        $('#enter_pin_box p.instructions').html('Za nastavak upišite PIN. Dobit ćete ga tako, da <strong>pošaljete SMS sa sadržajem PIN na broj 88302</strong>.');
                    }
                    //$.fn.colorbox({width:"282px", inline:true, href:"#insert-pin-container"});
				} else {
					$('#send_pin_box .error_box span').html(data.message);
					$('#send_pin_box .error_box').show();
					$('.registration .loader').hide();
					$('.registration .submit').removeAttr('disabled').fadeTo('fast',1);
				}
			}
		});
	});
	$('#enter_pin_submit').click(function(){
		$('#enter_pin_form').ajaxSubmit({
			url: '/register/verify-pin',
			dataType: 'json',
			success: function(data){
				if (data.success != false) {
					$('#enter_pin_box').hide();
					$('#enter_data_box').show();
					$('#msisdn3').val(data.msisdn);
					$('#operator3').val(data.operator);
					$('#pin3').val(data.pin);
					$('#user_id3').val(data.user_id);
					$('#terms3').val(data.terms);
				} else {
					$('#enter_pin_box .error_box span').html(data.message);
					$('#enter_pin_box .error_box').show();
					$('.registration .loader').hide();
					$('.registration .submit').removeAttr('disabled').fadeTo('fast',1);
				}
			}
		});
	});
    //change subscription
    $('#enter_pin_submit_change').click(function(){
		$('#enter_pin_form').ajaxSubmit({
			url: '/register/verify-pin/subscribe/0',
			dataType: 'json',
			success: function(data){
				if (data.success != false) {
					if (data.full) {
                        window.location = '/subscribe/full/' + data.full;
                    } else {
                        window.location = '/subscribe/free/1';
                    }
				} else {
					$('#change_subscription_box .error_box span').html(data.msg);
					$('#change_subscription_box .error_box').show();
					$('.registration .loader').hide();
					$('.registration .submit').removeAttr('disabled').fadeTo('fast',1);
				}
			}
		});
	});
    
	$('#create_profile_submit').click(function(){
		$('#enter_data_form').ajaxSubmit({
			url: '/register/createprofile',
			dataType: 'json',
			success: function(data){
				if (data.success != false) {
					window.location = '/home';
				} else {
					$('#enter_data_box .error_box span').html(data.message);
					$('#enter_data_box .error_box').show();
					$('.registration .loader').hide();
					$('.registration .submit').removeAttr('disabled').fadeTo('fast',1);
				}
			}
		});
	});
	$('.registration .submit').click(function(){
		$(this).attr('disabled','disabled').fadeTo('fast',0.5);
		$(this).next('.loader').show();
	});
	/*
		Miss slovenije banner change
	*/
	$('#miss-close').click(function(){
		$('#miss_slovenije').hide();
		$('#featured').show();
	});
    //$('.slideshow').cycle();
	/*
		Featured carousel
	*/
	if ($('#featured').length != 0) {
		$('#featured').jcarousel({
			scroll: 1,
			initCallback: mycarousel_initCallback,
			itemVisibleInCallback: paging_selected,
			buttonNextHTML: null,
	        buttonPrevHTML: null,
			auto: 5,
			wrap: 'last'
		});
	}
	/*
		Display painter on click
	*/
    $("a.hide_painter_preview").click(function() {
        var pido = $("a.hide_painter_preview").attr('rel');
        if (pido != "0") {
            $("#flash_wall_painter_teaser").hide();
            $("#flash_wall_painter").show();
        } else {
			$('#flash_wall_painter_teaser').hide();
			$('#painter_authentication').show();
            //alert($("a.hide_painter_preview").attr('title'));
        }
		return false;
    });
	if ($("#flash_wall_painter_teaser a").length != 0) {
	    $("#flash_wall_painter_teaser a").cycle('scrollLeft');
	}
	/*
		Astro sidebar horoscope
	*/
	$('#astro-signs').change(function(){
		$('#horoscope .horoscope_container').hide();
		$('#horoscope .horoscope_container.' + $('#astro-signs').val()).show();
	});
})

