/**
 *    Core Functions
 **/
var selected_img;

function header_next(el,item) {
	var speed = 300;
	if (!item) var item = 'a';
	var sel = el.find(item+'.sel');
	if (!sel) {
		el.find(item+':first').fadeIn(speed).addClass('sel');
	} else if (sel.next().length > 0) {
		sel.hide().removeClass('sel');
		sel.next().fadeIn(speed).addClass('sel');
	} else {
		sel.hide().removeClass('sel');
		el.find(item+':first').fadeIn(speed).addClass('sel');
	}
}

function header_prev(el,item) {
	var speed = 300;
	if (!item) var item = 'a';
	var sel = el.find(item+'.sel');
	if (!sel) {
		el.find(item+':first').fadeIn(speed).addClass('sel');
	} else if (sel.prev().length > 0) {
		sel.hide().removeClass('sel');
		sel.prev().fadeIn(speed).addClass('sel');
	} else {
		sel.hide().removeClass('sel');
		el.find(item+':last').fadeIn(speed).addClass('sel');
	}
}

function showTooltip(el,msg) {
	$('#tooltip_content').html(msg);
	$('#tooltip').css({left:el.position().left-$('#tooltip').width()+el.width()+10,top:el.position().top+el.height()}).show();
}

function hideTooltip() {
	$('#tooltip').hide();
}

function setThumb(url) {
	$.post(url,{},function (data) {
		$('#thumb').attr('src',data.filename);
	},'json');
}

function showChat(url,img) {
	chatPopup(url);
	$('#chats_status').attr('href','').attr('style','').html('<img src="'+img+'" alt="chats"/><span>0</span> Private Chats');
}

function submitClicked() {
	$.post();
}

function updateImg(data) {
	//alert(data);
}

function setDays(el) {
	days_in_month = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31};
	var daySelect = el.form['profile[birth][day]'];
	var selected = daySelect.selectedIndex;
	while (daySelect.length>0) daySelect.remove(0);
	for (i=1;i<=days_in_month[el[el.selectedIndex].value];i++) {
		var opt=document.createElement('option');
			opt.text=i;
			opt.value=i;
		try {
		    daySelect.add(opt,null); // standards compliant
		} catch(ex) {
		    daySelect.add(opt); // IE only
		}
	}
	daySelect.selectedIndex = selected;
}

/**
 *     User Defined Functions
 **/

function showHearts(el) {
	var all_hearts = $('#rating_box_id span a');
	var sel_heart = false;
	for(var i=0;i<all_hearts.length;i++) {
		if (sel_heart) all_hearts[i].className = 'bl_heart'; else all_hearts[i].className = '';
		if (all_hearts[i] == el) sel_heart = true;
	}
}

function hideHearts() {
	var all_hearts = $('#rating_box_id span a');
	var rating = $('#rating_box_id input').val();
	for(var i=0;i<all_hearts.length;i++) {
		if (i >= rating) all_hearts[i].className = 'bl_heart'; else all_hearts[i].className = '';
	}
}

function interestFocus(el) {
	var last = $('#interests textarea:last');
	last = last[0];
	if (el.target) el = el.target; else el = el[0];
	if (last.value == '' && last != el) return;
	var new_h = $(document.createElement('H4'));
		new_h.html("INTO:");
		$('#interests').append(new_h);
	var new_ta = $(document.createElement('TEXTAREA'));
		new_ta[0].name = "interest["+$('#interests textarea').length+"]";
		new_ta.focus(interestFocus);
		new_ta.blur(interestBlur);
		new_h.after(new_ta);
		var all_tas = $('#interests textarea');
		for (var i=0;i<all_tas.length; i++ ) {
			$(all_tas[i]).attr('name','interest['+i+']');
		}
}

function interestBlur(el) {
	if (el.target) el = el.target; else el = el[0];
	if (el.value == '') {
		$(el.previousSibling).remove();
		$(el).remove();
		var all_tas = $('#interests textarea');
		for (var i=0;i<all_tas.length; i++ ) {
			$(all_tas[i]).attr('name','interest['+i+']');
		}
	}
}

var oldFavIndex;
function setOldFav(index) {
	oldFavIndex = index;
}
function switchFavs(el, ev) {
	sels = $('#favorite_people_form select');
	for (i=0;i<sels.length;i++) {
		if (sels[i].selectedIndex == el.selectedIndex && el != sels[i]) {
			sels[i].selectedIndex = oldFavIndex;
		}
	}
	oldFavIndex =el.selectedIndex;
}

function checkTopten(el) {
	/*
	filter_class = el.className.substr(6);
	all_inputs = $('#topten_container_id input.'+filter_class);

	if (el.value == '') {
		for(i=0;i<all_inputs.length;i++) if (all_inputs[i].value != '') return;
		console.info('all empty');
	} else {
		h4_el = document.createElement('H4');
		// $('h4 selector').clone().appendTo(all_inputs[10]);
		// create input .. appendTo(h4_el) ......
	}
	*/
}

var topten_oldval;
function switchTopten(c) {
	all_inputs = $('#topten_container_id input._jq_sel_'+topten_oldval);
	for (i=0;i<all_inputs.length;i++) {
		all_inputs[i].name = "topten["+c+"]["+i+"]";
	}
}

function ajaxFileUpload(url) {
    //starting setting some animation when the ajax starts and completes
    $("#loading")
    .ajaxStart(function(){
        $(this).show().html('Uploading...');
    })
    .ajaxComplete(function(){
        //$(this).hide();
    });

    $.ajaxFileUpload
    (
        {
            url:url,
            secureuri:false,
            fileElementId:'fileToUpload',
            dataType: 'json',
            success: function (data, status)
            {
                if(typeof(data.error) != 'undefined')
                {
                    if(data.error != '')
                    {
                        $("#loading").html(data.error);
                    }else
                    {
                    	$("#loading").html('');
                    	switch (data.msg) {
                    		case 'OK':
                    			var anchor = document.createElement("A");
                    			anchor.href = "javascript:$.markItUp({openWith:'[ATTACHMENT]"+data.filename+"[/ATTACHMENT]'});";
                    			anchor.innerHTML = data.filename;
                    			$('#uploaded_files').append(anchor);
                    			$.markItUp({openWith:'[ATTACHMENT]'+data.filename+'[/ATTACHMENT]'});
                    		break;
                    	}
                    }
                }
            },
            error: function (data, status, e)
            {
            	//console.info(data);
                //console.info('ERROR2: '+e);
            }
        }
    )

    return false;

}

function ajaxUploadGalleryPhoto(url, container_id) {
    //starting setting some animation when the ajax starts and completes

    $("#"+container_id+'_status')
    .ajaxStart(function(){
        $(this).show();
    })
    .ajaxComplete(function(){
        //$(this).hide();
    });


    $.ajaxFileUpload
    (
        {
            url:url,
            secureuri:false,
            fileElementId:container_id,
            dataType: 'json',
            success: function (data, status)
            {
            	console.info(data);
                if(typeof(data.error) != 'undefined')
                {
                    if(data.error != '')
                    {
                    	$('#'+container_id+'_loader').html(data.error).show();
                    }else
                    {
                        //console.info('MSG: '+data.msg);
                    	switch (data.msg) {
                    		case 'OK':
                    			window.location.reload(true);
                    		/*
                    			var div_el = document.createElement('DIV');
                    				div_el.id = 'photo_'+data.photo_id;
                    			var img_el = document.createElement('IMG');
                        			img_el.src = data.filename;
                        			img_el.alt = data.caption;
                        			img_el.title = data.caption;
                        			$(div_el).append(img_el);
                        		var a_el = document.createElement('A');
                        			$(a_el).text('X').click(function() {
                        				removeGalleryPhoto(rem_url,data.photo_id)
                        			});
                        			$(div_el).append(a_el);
                        		$('#'+container_id).append(div_el);

                    			$('#'+photo_caption_id).val('');
                    			$('#'+file_id).val('');
                    			*/
                    		break;
                    		default:
		                   			location.reload(true);
                    	}
                    }
                }
            },
            error: function (data, status, e)
            {
            	console.info(data);
                //console.info('ERROR2: '+e);
            }
        }
    )

    return false;

}

function removeGalleryPhoto(url,id) {
	$.post(url,{id:id},function(data,status) {
		$('#photo_'+id).remove();
	});
}


function ajaxVideoUpload1(url,convert_url) {

	$('#status').show();

	$.ajaxFileUpload
	(
	    {
	        url:url+'upload_video.php',
	        secureuri:false,
	        fileElementId:'file',
	        dataType: 'json',
	        success: function (data, status)
	        {
	            if(typeof(data.error) != 'undefined')
	            {
	                if(data.error != '')
	                {
	                    //console.info('ERROR: '+data.error);
	                }else
	                {
	                	switch (data.msg) {
	                		case 'OK':
	                			$('#status').hide();
	                			var filename_el = $('#filename');
	                			filename_el[0].value = data.filename;
	                			var duration_el = $('#duration');
	                			duration_el[0].value = data.duration;
	                			//$('#upd_btn').
	                			//$('#upload_video_form_id').submit()
	                		break;
	                		default: //console.info(data);
	                	}
	                }
	            }
	        },
	        error: function (data, status, e)
	        {
	        	//console.info(data);
	            //console.info('ERROR2: '+e);
	        }
	    }
	)

	return false;

}

function reply_comment(id) {
    if ($('#comment_text_id').length) {
	   $('#comment_text_id').val('Re: <quote>'+$('#comment_'+id).text()+'</quote>');
    } else {
        tinyMCE.activeEditor.setContent('Re: <quote>'+$('#comment_'+id).text()+'</quote>')
    }
}

function chatPopup(url) {
	return window.open( url, null, "toolbar=0,scrollbars=0,location=0,menubar=0,status=1,height=240,width=747" );
}

function ajaxPostComment(url) {
	var text = $('textarea#comment_text_id').val();
	var rating = $('input#rating').val();
	$.ajax({
		url: url,
		type: 'POST',
		data: '_ci_nolabel=1&text='+text+'&rating='+rating,
		success: function(html) {
			$('#comments_box_id').html(html);
		}
	});
}

function ajaxRateComment(url) {
	var rating = $('input#rating').val();
	$.ajax({
		url: url,
		type: 'POST',
		data: '_ci_nolabel=1&rating='+rating,
		success: function(html) {
			$('#comments_box_id').html(html);
		}
	});
}

function detectMoreTab(sel) {
	var overflow = 0;
	var w = 0;
	var wrap = $(sel);
	var wrap_w = wrap.innerWidth() - 80;
	var tabs = wrap.children('li');
	$.each(tabs, function(index, el) {
		var i_w = $(el).width();
		w += i_w;
		if (w >= wrap_w) {
			overflow++;
			$(el).addClass('overflow');
		}
	});
	if (overflow > 0) {
		var moreLi = document.createElement('li');
		$(moreLi).addClass('more');
		$(moreLi).html('<a href="javascript:;"><span class="left">&nbsp;</span><span class="mid">+ More</span><span class="right">&nbsp;</span></a>');
		var items = $(wrap).find('li.overflow').detach();
		var ul = document.createElement('ul');
		$(ul).addClass('tabbedNav_more');
		$(items).appendTo(ul);
		$(ul).appendTo(moreLi);
		$(moreLi).appendTo(wrap);
		$(ul).find('span.left').detach();
		$(ul).find('span.mid').removeClass('mid');
		$(ul).find('span.right').detach();

		$(moreLi).hover(function() {
			$(moreLi).children('a:first').addClass('active');
			$(ul).slideDown('fast');
		}, function() {
			$(moreLi).children('a:first').removeClass('active');
			$(ul).slideUp('fast');
		});
		$(moreLi).click(function() {
			$(ul).slideToggle('fast');
		});
	}
}

var thumbs = new Array();
var thumbi = new Array();
var thumb_handle;
function rotateThumb(id,thumb,speed) {
	if (!speed) speed = 500;
	if (!thumbs[id]) thumbs[id] = thumb;
	if (!thumbi[id] || thumbi[id] >= 5) thumbi[id] = 0;
	thumbi[id] = thumbi[id] + 1;

	$('img#vid_'+id).attr('src', thumbs[id]+'-'+thumbi[id]+'.jpg');
	thumb_handle = setTimeout("rotateThumb('"+id+"', '"+thumbs[id]+"', "+speed+")", speed);
}
function stopRotation(id) {
	clearTimeout(thumb_handle);
	thumbi[id] = 0;
	$('img#vid_'+id).attr('src', thumbs[id]+'-'+thumbi[id]+'.jpg');
}

/* Gallery Thumbnail Rotator */
var gal_thumbs = new Array();
var gal_thumbi = new Array();
var gal_thumbs_base = new Array();
var gal_covers = new Array();
var gal_thumb_handle;
function rotateThumbs(id,base,speed) {
	if (!speed) speed = 500;
	if (!gal_thumbs[id]) {
		var thumbs = $('img#img_'+id).attr('rel');
		gal_thumbs[id] = jQuery.parseJSON(thumbs);
	}
	if (!gal_thumbi[id] || (gal_thumbi[id] == gal_thumbs[id].length)) gal_thumbi[id] = 0;
	if (!gal_thumbs_base[id]) gal_thumbs_base[id] = base;
	if (!gal_covers[id]) gal_covers[id] = $('img#img_'+id).attr('src');
	gal_thumbi[id] = gal_thumbi[id]+1;

	if (gal_thumbs[id][gal_thumbi[id]] != undefined) {
		$('img#img_'+id).attr('src', gal_thumbs_base[id]+gal_thumbs[id][gal_thumbi[id]]);
	}
	gal_thumb_handle = setTimeout("rotateThumbs('"+id+"')", speed);
}
function stopRotations(id) {
	clearTimeout(gal_thumb_handle);
	gal_thumbi[id] = 0;
	$('img#img_'+id).attr('src', gal_covers[id]);
}

var menu_timeout;
var menu_el;
$(document).ready(function(){
	$("a[href='#']").click(function(){
		return false;
	})
	$("a.new_window").click(function(){
		window.open ($(this).attr("href"),"mywindow" + new Date().getTime());
		return false;
	});


	$("li.menu_has_sub").hover(
		function() {
			clearTimeout(menu_timeout);
			$(this).addClass('sub_menu_hover').find('ul.sub_menu:first').fadeIn("fast");
		}, function() {
			menu_el = $(this);
			menu_timeout = setTimeout("menu_el.removeClass('sub_menu_hover')", 200);
		}
	);
});
