jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255]
	};
	
})(jQuery);




function cart_add(service,id)
{
	var vaclass ='.vid_'+service+'_'+id;

	$(vaclass+' .vcadd').hide();
	$(vaclass+' .vcremove').show();
	
	$.get(BASE_URL+'cart/add/'+service+'/'+id,false,function(data){
		
		if(data != 'fail')
		{
            if($('.panel_cart').css('display') == "block") {
                $(".panel_carousel").prepend(data);
            } 
            else 
            {
            // Show panel then hide it 
            $(".panel_cart").slideDown("medium",function(){ panel_resize();
             $(".panel_carousel").prepend(data);
            });
            
            setTimeout('panel()',2000);
            
            }   
			
		}
		
	});
	
	return false;
		
}

function cart_add_all(service,orderby,keywords,page)
{    
        
    $('.vcadd').hide();
	$('.vcremove').show();
    
    $.get(BASE_URL+'cart/addAllUnswiped/'+service+'/'+orderby+'/'+keywords+'/'+page,false,function(data){
		
		if(data != 'fail')
		{
            if($('.panel_cart').css('display') == "block") 
            {
                $(".panel_carousel").prepend(data);
            } 
            else 
            {
            // Show panel then hide it 
            $(".panel_cart").slideDown("medium",function()
            { 
             panel_resize();
             $(".panel_carousel").prepend(data);
            });
            
            setTimeout('panel()',2000);
            
            }   
			
		}
		
	});
	
	
    
    return false;
}


function cart_add_all_unswiped(service,orderby,keywords,page)
{    
        
    $('.vcunadded').hide();
	$('.vcunremoved').show();
    
    $.get(BASE_URL+'cart/addAll/'+service+'/'+orderby+'/'+keywords+'/'+page,false,function(data){
		
		if(data != 'fail')
		{
            if($('.panel_cart').css('display') == "block") 
            {
                $(".panel_carousel").prepend(data);
            } 
            else 
            {
            // Show panel then hide it 
            $(".panel_cart").slideDown("medium",function()
            { 
             panel_resize();
             $(".panel_carousel").prepend(data);
            });
            
            setTimeout('panel()',2000);
            
            }   
			
		}
		
	});
	
	
    
    return false;
}

function cart_remove_all(service,orderby,keywords,page)
{
    $('.vcremove').hide();
    $('.vcadd').show();
    
     $.get(BASE_URL+'cart/removeAll/'+service+'/'+orderby+'/'+keywords+'/'+page,false,function(data){
		
		if(data != 'fail')
		{
           
            if($('.videos ul li').size() != 0) {
	           $('.videos ul li').each( function () {
	                $('.vpid_'+$(this).attr("class") ).remove();
       	        }   
       	     )	
            }
       	}   
			
	});
	    
    return false;
}

function preview_cart_add(service,id)
{
	var vaclass ='.pvid_'+service+'_'+id;
	
	$(vaclass+' .pvadd').hide();
	$(vaclass+' .pvremove').show();
	
	return cart_add(service,id)
}

function cart_remove(service,id)
{
	var vaclass ='.vid_'+service+'_'+id;

	$(vaclass+' .vcremove').hide();
	$(vaclass+' .vcadd').show();
	
	$('.vpid_'+service+'_'+id).remove();
	
	$('.cvid_'+service+'_'+id).remove();
	
	
	$.get(BASE_URL+'cart/remove/'+service+'/'+id);
	
	if($('.videos ul li').size() == 0)
	{
	    document.location.href = BASE_URL+'cart';
	}
	
	return false;
			
}

function preview_cart_remove(service,id)
{
	var vaclass ='.pvid_'+service+'_'+id;
	
	$(vaclass+' .pvadd').show();
	$(vaclass+' .pvremove').hide();
	
	return cart_remove(service,id)
}

function preview_cart_edit()
{
	// just show edit form and hide other stuff
	$(".cpv_title , .cpv_description , .cpv_tags , .cpv_actions").hide();
	$(".cpv_title_edit , .cpv_description_edit , .cpv_tags_edit , .cpv_edit").show();
}


function cart_save_all()
{
    var uatitle = $('#uatitle').val();
    var uadesc = $('#uadesc').val();
    var uatags = $('#uatags').val();
        
    if(!confirm("Are you shore you wish to update meta for all videos ?"))
    {
        return false;        
    }
    
    $.post(
    BASE_URL+'cart/saveAll/',
	{title:uatitle,description:uadesc,tags:uatags},
	function (data) {
	   if(data == "success") {
	       document.location.href = BASE_URL+'cart';
	   }
	   else alert('There was an error updating.');
	}
	);
	
	return false;
		
       
}
function preview_cart_save(service,id)
{
	// just show edit form and hide other stuff
	vtitle = $(".cpv_title_edit input").val();
	vdescription = $(".cpv_description_edit textarea").val();
	vtags = $(".cpv_tags_edit input").val();
	
	if(vtitle.length == 0 )
	{
		alert('Video Title cannot be empty.');
		return false;
	}
	
	if(vdescription.length == 0 )
	{
		alert('Video description cannot be empty.');
		return false;
	}
	
	if(vtags.length == 0 )
	{
		alert('Video Tags cannot empty.');
		return false;
	}
	
	$.post(BASE_URL+'cart/save/'+service+'/'+id,
	{title:vtitle,description:vdescription,tags:vtags},
	function (data) {
		// replace html
		content = data.split('<!--more-->');
				
		$(".preview_info").html(content[0]);
		
		$(".cvid_"+service+"_"+id).html(content[1]);
		
	}
	);

}


function preview_cart_cancel()
{
	// just show edit form and hide other stuff
	$(".cpv_title , .cpv_description , .cpv_tags , .cpv_actions").show();
	$(".cpv_title_edit , .cpv_description_edit , .cpv_tags_edit , .cpv_edit").hide();
}


function preview(service,id)
{
	var url = BASE_URL+'videos/apreview/'+service+'/'+id+'/?height=400&width=800';

    tb_show('Preview Video',url);
    
    return false;
}


function cpreview(service,id)
{
	var url = BASE_URL+'cart/apreview/'+service+'/'+id+'/?height=400&width=800';

    tb_show('Preview Video',url);
    
    return false;
}
        
var panel_visible=false;
var video_width = 120;


function panel_resize()
{
	var width  = $(".panel").width() - 100 ;
		
	var visible_videos = Math.round(width/video_width) - 1;
		
	$(".panel_carousel_envolope").width( visible_videos * video_width );
	$(".panel_center").width( visible_videos * video_width +100);
}
function panel()
{
	
	if($('.panel_cart').css('display') == "block") {
		// Hide panel
		$(".panel_cart").slideUp("medium");
	} 
	else 
	{
		// Show panel
		$(".panel_cart").slideDown("medium",function(){
		panel_resize();
		});
	}
	return false;
}

function panel_move_right()
{
	// get total videos 
	var videos = $(".panel_carousel li").length;
	var width  = $(".panel_carousel_envolope").width();
	var left =  -parseInt($(".panel_carousel").css('left'));
	
	var visible_videos = Math.round(width/video_width);
		
	max_move = visible_videos - 1 ;
	
	
	last_video = Math.round(left/video_width) + visible_videos;
	
	remain = videos - last_video;
	
	
	if(remain == 0|| videos < visible_videos) {
		return false;
	}
	
	if(remain <= max_move) 
	{
		left = left + (remain * video_width);
		$(".panel_carousel").animate({  left: -left}, 500);
		return false;
	}
	
	if(remain > max_move) 
	{
		left = left + (max_move * video_width);
		$(".panel_carousel").animate({  left: -left}, 500);
		return false;
	}
	
	return false;
}

function panel_move_left()
{
	// get total videos 
	var videos = $(".panel_carousel li").length;
	var width  = $(".panel_carousel_envolope").width();
	var left =  -parseInt($(".panel_carousel").css('left'));
	
	var visible_videos = Math.round(width/video_width);
		
	max_move = visible_videos - 1 ;
	
	fist_video = Math.round(left/video_width);
	
	remain = fist_video;
	
	if(remain == 0|| videos < visible_videos) {
		return false;
	}
	
	if(remain <= max_move) 
	{
		left = -left + (remain * video_width);
		$(".panel_carousel").animate({  left: left}, 500);
		return false;
	}
	
	if(remain > max_move) 
	{
		left = -left + (max_move * video_width);
		$(".panel_carousel").animate({  left: left}, 500);
		return false;
	}
	
	return false;
}


function setView(type)
{
	if(type==0)
	{
		$('.video_list').hide();
		$('.video_grid').show();
		$.cookie('video_view',1);
	} 
	else 
	{
		$('.video_grid').hide();
		$('.video_list').show();
		$.cookie('video_view',0);		
	}
	return false;
}

function getCats(site_id)
{

var cat_id = site_id.value;
if(cat_id == "")
{
    $("#checkout_cats").hide();
    $("#checkout_cats").html("");
    return;   
}

$.get(BASE_URL+'cart/getCatDD/'+cat_id,false,function(data){

    $("#checkout_cats").html(data);
    $("#checkout_cats").show();

});

}


function updateProgress(checkout_id)
{
    
    $.ajax({
    type: "GET",
    url: BASE_URL+'cart/process_status/'+checkout_id,
    dataType: "json",
    async : true,
    success : function(json) {
        
        // move progress bar 
        if(json.done != 0 )
        {
            pos = 400 - ( 4 * json.done );
            //alert(json.done);
            $('#progressbar').css('background-position',"-"+pos+"px 0px");
            
            $('#progressstatustext').html("Submitting ... ");
            
        }
        
        if(json.done != 100)
        {
            setTimeout('updateProgress('+checkout_id+')',1000);
        } 
        else {
            // done show completed and change status 
                        
            $('#progressstatustext').html("Submission Finished");
            $('#buttonbackground').hide();
            $('#buttonclose').show();
                       
            
        }
        
        
    }
})


    /*$.getJSON(BASE_URL+'cart/process_status/'+checkout_id,false,function(json) {

        alert('here' + json);
        alert(json.done);
        
        if(json.done != 100)
        {
            setTimeout('updateProgress('+checkout_id+')',2000);
        }
               
    });*/
    
}

function start_posting()
{
    checkout_id = $('#checkout_id').val();
    setTimeout('updateProgress('+checkout_id+')',1000);
    
    $.ajax({  type: "GET",  url: BASE_URL+'cart/process_start/'+checkout_id,  timeout : 1000 })

    
    // $.get(BASE_URL+'cart/process_start/'+checkout_id);

    
    // if dialog exists start updating proces
    // Fire first start request
}

function start_checkout(site_id,cat_id)
{
	// Display modal with warning dont close 
	
	var url = BASE_URL+'cart/process/'+site_id+'/'+cat_id+'/?height=180&width=410&modal=true';

    tb_show('Submitting Videos ...',url,"",start_posting);
        
    return false;
}

function cart_update_all()
{
    var url = BASE_URL+'cart/saveAll/?height=400&width=450';

    tb_show('Update all Videos',url);
    
    return false;
    
}


