// just some html, here for convenience
// this is a global var
var ajaxLoaderTag = '<img src="/images/ajaxLoader.gif" class="spinner"/>';

// store the URL of the currently selected category -- makes it easier to
// update the category again when modifying links
var currentCategoryURL = '';

$(document).ready( function() {


	////////////////////


	//////****** set the change in sequence of links ******//////////


/* $(".draggableDiv").draggable({

    drag: function() {

		}
});*/

	///////////////////
    // Contact form {{{
   /* $('#contactForm').submit( function() {

        $('#contactForm').fancyForm({
            postSuccess: function( responseText ) {
                if( responseText.Saved == true ) {
                    $('#Box_Contact').empty();
                    $('#Box_Contact').html( '<h4>Contact Me</h4><p>Your message will be delivered soon.</p>' );
                }
             }
        });
        return false;
    });*/// }}}
    // Clear error markings from input fields when they're focused {{{
        $('.Error').livequery( 'focus', function() {
            $(this).removeClass('Error');
            $('label[for='+$(this).attr('id')+']').removeClass('Error');
        });
    // }}}
    // clicking on the category list {{{
    // select (and load) that category into the div panel below to show the
    // links in that category
    $('#CategoryList ul li a.CategoryLink').live( 'click', function( event ) {
		//alert('suceess');
        if( isLClick( event )) { return; }
        //selectCategory( $(this).attr('href') );
        return false;
    });// }}}
    // clicking on the friends list {{{
   /* $('#Box_Friends ul li a.pagination').live( 'click', function( event ) {
		//alert('hi');
        if( isLClick( event )) { return; }
        $('#Box_Friends ul').html( ajaxLoaderTag );
        $('#Box_Friends ul').fadeOut('fast');
        $.ajax({
            url: this.href,
            cache: false,
            success: function( result ) {
                $('#Box_Friends ul').html( result ).fadeIn('fast');
            }
        });
        return false;
    }); // }}}
    // clicking on the LARGE friends list {{{
  $('#Box_LargeFriends ul li a.pagination').live( 'click', function( event ) {
		//alert('hi');
        if( isLClick( event )) { return; }
        $('#Box_LargeFriends ul').fadeOut('fast');
        $.ajax({
            url: this.href,
            cache: false,
            success: function( result ) {
                $('#Box_LargeFriends ul').html( result ).fadeIn('fast');
            }
        });
        return false;
    }); // }}}*/
    // Link popups {{{
    // FUCK YOU, MICROSOFT, your z-index handling blows
    // the margin-left and margin-top stuff is to keep the popups from
    // appearing off screen
    $('div.SquishImageWrapper').livequery( function() {
		//alert('hi');
        $(this).hover(
            function() {
                // Entering
                if( $.browser.msie ) {
                    $(this).css({ 'z-index' : '3' });
                    $('.PopupContent').css({ 'z-index' : '3' });
                }

                var offset  = $(this).offset();
                var pWidth  = $(this).children('.PopupContent').outerWidth();
                var pHeight = $(this).children('.PopupContent').outerHeight();
                var right  = $(window).width()  + $(window).scrollLeft();
                var bottom = $(window).height() + $(window).scrollTop();

                if( offset.left + pWidth > right ) {
                    var toMove = right - ( offset.left + pWidth ) - 14;
                    $(this).children( '.PopupContent' ).css({ 'margin-left' : toMove });
                }

                if( offset.top + pHeight > bottom ) {
                    var toMove = bottom - ( offset.top + pHeight ) - 14;
                    $(this).children( '.PopupContent' ).css({ 'margin-top' : toMove });
                }

                $(this).children('.PopupContent').fadeIn('medium');

            },
            function() {
                // leaving
                if( $.browser.msie ) {
                    $(this).css({'z-index':'0'});
                    $('.PopupContent').css({ 'z-index' : '0' });
                }
                $('.PopupContent').stop( true, true );
                $(this).children('.PopupContent').hide();
                $(this).children('.PopupContent').css({ 'margin-top' : '0' });
                $(this).children('.PopupContent').css({ 'margin-left' : '0' });
            }
        );
    });
    // }}}
    // nyroModal popups {{{
    $('a.modal').live( 'click', function( event ) {
    	if( isLClick( event )) { return; }
        event.preventDefault();
        $('.PopupContent').hide();
        $(this).nyroModalManual({
            autoSizeable: true,
            resizable: true,
            minWidth: 10,
            minHeight: 10,
            padding: 40
        });
        return false;
    });
    // }}}


	/////////////////////////////////

	///////////////////////////////
});
function switchRatingToStars() { // {{{
    if( $('.PopupRating').length <= 0 ) { return; }
    $('.LinkRatingForm').stars({
        inputType: 'select',
        callback: function( ui, type, value, event, formID ) {
            fID = $('#'+formID);
            fID.fancyForm({
                postSuccess: function( response ) {
                    if( response.Saved == true ) {
                        refreshLinkInfo( response.LinkID );
                    }
                }
            });
        }
    });
    $('.LinkRatingForm').each( function() {
        var average    = $(this).find('input[name="average"]').val();
        var hasAverage = $(this).find('input[name="average"]').val().length;
        var hasVoted   = $(this).find('input[name="hasVoted"]').val();
        if( hasVoted == 0 && hasAverage != 0 ) {
            $(this).data('stars').set( average, true );
        }
    });
    $('.RatingSubmit').hide();
}
// }}}

/*function selectCategory( URL ) { // {{{
    if( '' == URL ) { return selectFirstCategory(); }
    currentCategoryURL = URL;
    $('#CategoryLinkContainer').empty();
    $('#CategoryLinkContainer').html( ajaxLoaderTag );
    hlCategory( URL );
    $.ajax({
        url: URL,
        cache: false,
        success: function( result ) {
            $('#CategoryLinkContainer').empty();
            $('#CategoryLinkContainer').html( result );
            makeFancy();
        }
    });
} */// }}}
function makeFancy() { // {{{
    switchRatingToStars();
    equalHeight( $('.SquishLink' ) );
    equalWidth( $('.SquishLink' ) );
    fixFavicon();
    makeLinkTitleTooltips();
} // }}}
function fixFavicon() { // {{{
    $('.PopupFavicon').preload({
        placeholder: '/images/missing_favicon.png',
        notFound: '/images/missing_favicon.png'
    });
} // }}}
/*function selectCategoryByID( id ) { // {{{
    selectCategory( $('li#Category_'+id+' a').attr('href') );
} /// }}}
function selectFirstCategory() { // {{{
    selectCategory( $('#CategoryList ul li.Sortable a.CategoryLink:first').attr('href') );
} // }}}
function hlCategory( URL ) { // {{{
    $('#CategoryList ul li a').each( function() {
        if( $(this).attr('href') == URL ) {
            $(this).addClass('SelectedCategory');
        } else {
            $(this).removeClass('SelectedCategory');
        }
    });
} */// }}}
function equalHeight( group ) { // {{{
    tallest = 0;
    group.each( function() {
        thisHeight = $(this).height();
        if( thisHeight > tallest ) {
            tallest = thisHeight;
        }
    });
    group.height( tallest );
} // }}}
function equalWidth( group ) { // {{{
    widest = 0;
    group.each( function() {
        thisWidth = $(this).width();
        if( thisWidth > widest ) {
            widest = thisWidth;
        }
    });
    group.width( widest );
} // }}}
function isLClick( event ) { // {{{
    // Detection for whether a click was made with only the left button, and without any modifiers
    if( event.button != 0 || event.ctrlKey || event.shiftKey || event.altKey ) {
        return true;
    } else {
        return false;
    }
} // }}}
function refreshLinkInfo( id ) { // {{{
    $.ajax({
        type: 'GET',
        url: '/link/refreshInfo/?id='+id,
        success: function( response ) {
            $('#Link_'+id+' * img.SquishImage').each( function() {
                $(this).attr('src', response.Thumbnail );
            });
            if( !response.Rating ) {
                $('#Link_'+id+' * div.PopupRatingDisplay').html( 'Nobody has rated this link' );
            } else {
                $('#Link_'+id+' * div.PopupRatingDisplay').html( 'Rating average of '+response.Rating.Average+' stars by '+response.Rating.Total+' users' );
            }
            $('#Link_'+id+' * div.PopupViewCount').html( 'Viewed '+response.ViewCount+' times' );
        },
        cache: false,
        dataType: 'json'
    });
} // }}}
function makeLinkTitleTooltips() { // {{{
    $('div.LinkTitle span').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        opacity: 1,
        showBody: '|',
        top: -15,
        fade: 250
    });
} // }}}


//////////////////////////
 $(document).ready(function(){
	// selectCategory( '' );
	 var tit = "";
       // $("#move").draggable();
	/*   $("#Box").draggable({


    drag: function() {
		 tit = this.title;
		 alert(tit);
		//alert('dragged');
		}
});*/

// $('.LinksList').draggable({helper: 'clone'});

/*$(".SquishLink").draggable ({

    drag: function(ev, ui) {
		//alert('hi');
	}*/
});





$(".Sortable").droppable ({

    drop: function(ev, ui) {

	 // alert(ui.draggable.attr('id'));
	     var link = ui.draggable.attr('id')
		 var category = this.id;
		 var linkid = explode('Link_', link);
		var linkIdVal = ltrim(linkid,',');

		var categoryid = explode('Category_', category);
		var categoryIdVal = ltrim(categoryid,',');

		  $.ajax({
		  url: "http://test.esquish.com/link/"+linkIdVal+"/edit",
		  //context: document.body,
		  success: function(data){
			///$(this).addClass("done");
			$('#hiddenId').html(data);
			//alert(data);

			/////////////////////////


				///event.preventDefault();

    /* get some values from elements on the page: */
	//alert('hel');
   /// var $form = $( this ),
   var category_id = document.getElementById('link_category_id').value;
			var link_id = document.getElementById('link_id').value;
			// var isJS = "1";
			var link_url = document.getElementById('link_url').value;
			var link_title = document.getElementById('link_title').value;
			var link_description = document.getElementById('link_description').value;
			var link_tags = document.getElementById('link_tags').value;
			var link__csrf_token = document.getElementById('link__csrf_token').value;

			var category_id = document.getElementById('link_category_id').value;

			$.post( "http://test.esquish.com/link/"+linkIdVal, { "link[category_id]" :categoryIdVal , "link[description]":link_description , "link[id]":link_id ,"link[tags]":link_tags ,"link[title]":link_title,"link[url]" :link_url ,"link[_csrf_token]":link__csrf_token,"isJS":"1","sf_method":"put"},
      function( data1 ) {
				 var pathname = window.location.pathname;
//alert(pathname);
         /// var content = $( data ).find( '#content' );
        ///  $( "#result" ).html( content );
		///$('#Box_LargeFriends ul').html( '{"Saved":true,"Message":"Your link has been moved"}' ).fadeIn('fast');
		//alert('Updated Successfully');
		//var attrVal = $(".SelectedCategory").attr("id");
		//var hrefVal = $(".SelectedCategory").attr("href");

			//selectCategory( hrefVal );
			//selectCategory( 'http://test.esquish.com/sharad/1170' );
			//alert($(this).attr('href'));
			//selectCategory( 'http://test.esquish.com' );
			//$("#"+attrVal).addClass('SelectedCategory');

			 return false;
//window.location.href=window.location.href;
			//var dataVal = data.getElementById('link_title').value;
			//alert(dataVal);
		 // }
		});
			////////////////////////
		  }
		});


		}
});
   /* });*/





	function explode (delimiter, string, limit) {

    var emptyArray = {        0: ''
    };

    // third argument is not required
    if (arguments.length < 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined') {        return null;
    }

    if (delimiter === '' || delimiter === false || delimiter === null) {
        return false;    }

    if (typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object') {
        return emptyArray;
    }
    if (delimiter === true) {
        delimiter = '1';
    }
     if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }}


function ltrim (str, charlist) {
    // Strips whitespace from the beginning of a string
    //
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/ltrim    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: ltrim('    Kevin van Zonneveld    ');    // *     returns 1: 'Kevin van Zonneveld    '
    charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    var re = new RegExp('^[' + charlist + ']+', 'g');
    return (str + '').replace(re, '');
}





