var file_id = 0;
var flag = 0;
var def_id_g;
var selEl;
var showblock = function(lincc, show_element) {
selEl = show_element;
	var element = document.getElementById(show_element);
	if (element.style.display == "block") {
		element.style.display = "none";
    flag = 0;
		return;
	}
	if (element.style.display == "" || element.style.display == "none") {
		element.style.display = "block";
		lincc.className = "open";
    flag = 1;
	}
	else {
		element.style.display = "none";
		lincc.className = "";
	}
	// Log in or Sing up
	var login = document.getElementById("login");
	var forgot = document.getElementById("forgot");
	if (show_element == "login" || show_element == "forgot") {
		if (show_element == "login" && forgot.style.display == "block") {
			login.style.display = "none";
			forgot.style.display = "none";
			lincc.className = "";
		}
		if (show_element == "forgot") {
			document.getElementById("login").style.display = "none";
		}
	}

	//Theme icons
	if (show_element == "selectbox") {
		var selc = document.getElementById("selectoption");
		var opts = document.getElementById("selectbox").getElementsByTagName("a");
		for (i=0; i < opts.length; i++) {
				opts[i].onclick = function() {
				selc.value = this.firstChild.nodeValue;
				smilesLoad(this.id, 1, 0);
			}
		}
	}

	if (show_element.match("muzcodes") || element.style.display == "block") {
		var i=1;
		while (document.getElementById("muzcodes" + i)) {
			document.getElementById("muzcodes" + i).style.display = "none";
			i++;
		}
			element.style.display = "block";
	}
}

function changeFilename( id, change, save )
{
  var file_text = $( '#file_name_'+id ).html();
  $( '#change_'+id ).empty();
  $( '#change_'+id ).html('<form method="post" id="form_'+id+'"><input type="hidden" name="fileId" value="'+id+'" /><input style="width: 200px;" type="text" value="'+file_text+'" name="filename" />&nbsp;<a href="#" onclick="subFormChange('+id+')">'+save+'</a></form>');
  //$( '#change_'+id ).empty();
  //$( '#change_'+id ).html('</a>');
  //<input type="submit" value="'+change+'" />
}

function subFormChange( id )
{
  $("#form_"+id).submit();
}

function hideMenu()
{
  if( selEl != undefined && undefined !=  "login" &&  selEl != "forgot" &&  selEl != "colors")
  {
    var element = document.getElementById(selEl);

  	if ( flag >= 2 && element.style.display == "block" && selEl != "login" &&  selEl != "forgot" &&  selEl != "colors") {
      element.style.display = "none";
      flag=0;
      selEl = undefined;
  		return;
  	}
    if( flag != 0)
    {
      flag++;
    }
  }



}
//function for edit muzicon
var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
function pnufl(){
 	var musicon_v_srvObj = isInternetExplorer ? document.all.musicon_v_srv : document.musicon_v_srv;


  //'&nomuz='.$tmpNomuz.'&site=http://'.$_SERVER['SERVER_NAME'].'/&icon_pic='.$data['ids'].'.'.$data['sext'].'&music_file='.$data['id'].'&bg_color='.$data['bgcolor'].'&type_of_clip='.$data['type'].'&text_color=FFFFFF&text_message='.str_replace('"', '&quot;', $data['mood'])
  //alert('fdsd');
 //alert( "icon_pic="+window.document.getElementById("ids").value+".png&text_message="+window.document.getElementById("mood").value+"&type_of_clip="+window.document.getElementById("type").value+"&bg_color="+window.document.getElementById("bgcolor").value+"&text_color=FFFFFF&music_file=AXACcEYM" );
 if( window.document.getElementById("bgcolor").value == '' )
 {
   window.document.getElementById("bgcolor").value = '898989';
 }

	musicon_v_srvObj.SetVariable("srv", "text_message="+window.document.getElementById("mood").value+"&type_of_clip="+window.document.getElementById("type").value+"&bg_color="+window.document.getElementById("bgcolor").value+"&icon_pic="+window.document.getElementById("ids").value+".png");

	//musicon_v_srvObj.SetVariable("srv", ");
  //alert(window.document.getElementById("bgcolor").value);
 // musicon_v_srvObj.SetVariable("srv", "bg_color="+window.document.getElementById("bgcolor").value);
  //"icon_pic=1.png&music_file=AXACcEYM&bg_color=898989&type_of_clip=simple_text&text_color=FFFFFF&text_message=Booo..");
	//musicon_v_srvObj.SetVariable("srv","icon_pic=1.png&music_file=AXACcEYM&bg_color=ff0000&type_of_clip=simple_text&text_color=FFFFFF&text_message=Booo..");
}

function upload_muzicon(lext) {
//alert('work it');
    arr  = lext.split('|');
    flen = document.getElementById('filepath').value.length;
    ext  = document.getElementById('filepath').value.substring(flen-3, flen);
    ext  = ext.toLowerCase();
    done = 0;

    for (i in arr) {
        if (ext == arr[i]) done++;
    }
    if (done>0) {
        window.document.getElementById('uploading').style.display='block';
        window.document.getElementById('choosefile').style.display='none';
        window.document.getElementById('uploaderror').style.display='none';
        if (window.document.getElementById('mood').value=="insert text") window.document.getElementById('mood').value='';
        window.document.upl_form.submit();
    } else {
        window.document.getElementById('uploaderror').style.display='block';
    }
}

function upload_error(text) {
    window.document.getElementById('uploading').style.display='none';
    window.document.getElementById('choosefile').style.display='block';
    window.document.getElementById('uploaderror2').innerHTML=text;
    window.document.getElementById('uploaderror2').style.display='block';
    return false;
}

function upload_url() {
    var x = '';
    x = prompt('', 'http://');
    if (x && x != 'http://') {
        window.document.getElementById('url').value=x;
        window.document.getElementById('upload').value=2;
        upload_muzicon();
    }
}

function new_upload(mood, file) {
    window.document.getElementById('upload').value=1;
    document.getElementById('filepath').value = file;
    window.document.getElementById('uploading').style.display='none';
    window.document.getElementById('upload_done').style.display='none';
    window.document.getElementById('choosefile').style.display='block';
    window.document.getElementById("id").value = '';
    window.document.getElementById("ids").value = 0;
    window.document.getElementById("umood").value = mood;
    window.document.getElementById("mood").value = '';
    window.document.getElementById("bgcolor").value = '';
    preview();
    //pnufl();
    return false;
}

function upload_done() {
	window.document.getElementById('choosefile').style.display='none';
    window.document.getElementById('uploading').style.display='none';
    window.document.getElementById('upload_done').style.display='block';
    preview();
    //pnufl();
    return false;
}

function choosesmile(ids, mood, text) {
	URLInputed("mp3");
    window.document.getElementById("ids").value = ids;
    if (text==window.document.getElementById("umood").value) {
        window.document.getElementById("mood").value = mood;
    }
    preview();
    //pnufl();
    return false;
}

function change_color(obj) {
	URLInputed("mp3");
    if (obj.currentStyle) {
        var color = obj.currentStyle.backgroundColor.substring(1,7);
    } else if(window.getComputedStyle) {
        var color = window.getComputedStyle(obj, null).getPropertyValue("background-color");
        var rgbValue = color.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/);
        color = colorTable(parseInt(rgbValue[1]),parseInt(rgbValue[2]),parseInt(rgbValue[3]))
    } else{
        var color = obj.currentStyle.backgroundColor.substring(1,7);
    }
    window.document.getElementById("bgcolor").value = color;
    preview();
    //pnufl();
    return false;
}

function colorTable(red, green, blue) {
    red = red.toString(16);
    if (red.length == 1)
        red = '0' + red;
    green = green.toString(16);
    if (green.length == 1)
        green = '0' + green;
    blue = blue.toString(16);
    if (blue.length == 1)
        blue = '0' + blue;
    return red + green + blue;
}

function change_type(obj) {
	URLInputed("mp3");
    window.document.getElementById("type").value = obj.value;
    preview();
    //pnufl();
    return false;
}

function change_mood(obj, text) {
	window.document.getElementById("mood").value = obj.value;
    if (obj.value=='') {
        obj.value = text;
    }
    preview();
    //pnufl();
    return false;
}

function preview() {
    //if (window.document.getElementById("id").value!='') {
       // alert( window.document.getElementById("mood").value );
	    //alert(def_id_g);
		
        if( file_id != 0 )
        {
          all = 'ids='+window.document.getElementById("ids").value+'&mood='+window.document.getElementById("mood").value+'&type='+window.document.getElementById("type").value+'&bgcolor='+window.document.getElementById("bgcolor").value+'&ident='+file_id+ '&autostart=' + $('#autostart').val() + "&def_id=" + def_id_g;
        }
        else
        {
          all = 'ids='+window.document.getElementById("ids").value+'&mood='+window.document.getElementById("mood").value+'&type='+window.document.getElementById("type").value+'&bgcolor='+window.document.getElementById("bgcolor").value + '&autostart=' + $('#autostart').val() + "&def_id=" + def_id_g;
        }

        PreviewLoad(window.document.getElementById("id").value, all, def_id_g);
    //}
    return false;
}

function save_muzicon() {
    if (window.document.getElementById("id").value!='') {
        all = 'ids='+window.document.getElementById("ids").value+'&mood='+window.document.getElementById("mood").value+'&type='+window.document.getElementById("type").value+'&bgcolor='+window.document.getElementById("bgcolor").value+ '&autostart=' + $('#autostart').val()+'&ident='+file_id;
        MuziconSave(window.document.getElementById("id").value, all);
    }
    return false;
}

function ltrim( val )
{

  var ptrn = /\s*((\S+\s*)*)/;
  return val.replace(ptrn, "$1");

}

function rtrim( val )
{

  var ptrn = /((\s*\S+)*)\s*/;
  return val.replace(ptrn, "$1");

}

function trim( val )
{

  return ltrim( rtrim( val ) );

}

function selectImage( id, item )
{
  if( item == undefined )
  {
    item = '';
  }
  else
  {
    item = '_'+item;
  }
 /* $("#selImage"+item).empty();
  $("#selImage"+item).html('Waiting...');
  $.post(
    "http://"+url+"/admin/index.php",
    {
      s:    "ajax",
      ev:   "getImage",
      ident: id
    },
    function ( data )
    {*/
      $("#selImage"+item).empty();
      $("#selImage"+item).html('<img src="http://'+window.document.location.hostname+'/upload/fotobank/'+id+'"  alt="'+id+'"/>');
 //   }
 // );
}

function uploadFlash( widht, height )
{
 // alert( $('#choosemusic').html() );
  if( $('#choosemusic').html() == null )
  {
    $('#choosemusic').empty();
    $(document).ready(function(){
      $('#choosemusic').flash(
          { src: 'FUPL.swf',
            width: widht,
            height: height,
            allowScriptAccess: 'always',
            id: 'FUPL',
            flashvars: { ids: window.document.getElementById('ids').value, mood: window.document.getElementById('mood').value, type:  window.document.getElementById('type').value, bgcolor: window.document.getElementById('bgcolor').value, file_id: file_id }
          },
          { version: 9 }
      );
   });
  }
}

function changeSizeFlash(width, height)
{
  $('#FUPL').width(width);
  $('#FUPL').height(height);
}

function addFlashVars()
{
  alert('addFlashVars');

  var ids     = window.document.getElementById('ids').value;
	var mood    = window.document.getElementById('mood').value;
	var type    = window.document.getElementById('type').value;
	var bgcolor = window.document.getElementById('bgcolor').value;

  alert( $('#FUPL').width );
  $('#FUPL').flashvars("ids="+ids+"&mood="+mood+"&type="+type+"&bgcolor="+bgcolor );

}

function resetFileId()
{
  file_id = 0;
  $.post("preview.php",
    {
        ids: window.document.getElementById("ids").value,
        mood: window.document.getElementById("mood").value,
        type: window.document.getElementById("type").value,
        bgcolor: window.document.getElementById("bgcolor").value
    },
    function(data){
      $('#previewblock').html(data);
    }
  );
}

function showPre(id)
{
  if( id != '' || ident != 0 )
  {
    file_id = id;
    var type = window.document.getElementById("type").value;
    $.post("preview.php",
      { ident: id,
        ids: window.document.getElementById("ids").value,
        mood: window.document.getElementById("mood").value,
        type: window.document.getElementById("type").value,
        bgcolor: window.document.getElementById("bgcolor").value
        },
      function(data){
        $('#previewblock').html(data);
      }
    );
  }
}

function showPreAnoth(id)
{
  if( id != '' || ident != 0 )
  {
    file_id = id;
    var type = window.document.getElementById("type").value;
    $.post("preview.php",
      { id: id,
        ids: window.document.getElementById("ids").value,
        mood: window.document.getElementById("mood").value,
        type: window.document.getElementById("type").value,
        bgcolor: window.document.getElementById("bgcolor").value
        },
      function(data){
        $('#previewblock').html(data);
      }
    );
  }
}

function changeLang(lang)
{
 // $.cookie('lang', lang);
  var date = new Date();
  date.setTime(date.getTime()+(366*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
  document.cookie = "lang="+lang+expires+"; path=/";
  location.href = 'http://'+window.document.location.hostname;
}

function copyLinkTagoo(href)
{
    $("#music_url").attr({'value': href});
}

function URLInputed(lext)
{
    if (!lext) lext='mp3';
	arr  = lext.split('|');
    flen = document.getElementById('music_url').value.length;
    ext  = document.getElementById('music_url').value.substring(flen-3, flen);
    ext  = ext.toLowerCase();
    done = 0;

	var mu = window.document.getElementById("music_url").value;

    var ftptest = document.getElementById('music_url').value.substring(0, 3);
    var httptest = document.getElementById('music_url').value.substring(0, 4);

    for (i in arr) {
        if (ext == arr[i]) done++;
    }

    if (ftptest!='ftp' && httptest!='http')
    {        		
		ftptest = document.getElementById('msc_url').value.substring(0, 3);
		httptest = document.getElementById('msc_url').value.substring(0, 4);
		
		if (ftptest!='ftp' && httptest!='http')
		{			
			done=-1;
		}
		else
		{
			done=1;
			mu = window.document.getElementById("msc_url").value;
		}
    }
	
	var auto = 0;
	
	if ($('#autostart_checkbox').attr("checked") == true)
	{
		auto = 1;
	}

    if (done>0) {
        window.document.getElementById('uploaderror').style.display='none';
        if (window.document.getElementById('mood').value=="insert text") window.document.getElementById('mood').value='';

	    $.post("upload.php",
	      { 'url_input' : 1,
	        mood: window.document.getElementById("mood").value,
	        type: window.document.getElementById("type").value,
	        bgcolor: window.document.getElementById("bgcolor").value,
			music_url : mu,
			song_name : window.document.getElementById("song_name").value,
			autostart : auto
	        },
	      function(data){
		  	p_data = data.split('|');
			id = p_data[0];
			cid = p_data[1];
			ident = p_data[2];
		  	window.document.getElementById('id').value=cid;
	        //showPreAnoth(id);
			preview();
	      }
	    );

    } else {
        window.document.getElementById('uploaderror').style.display='block';
    }
}

function toggleAutostart()
{
	if ($('#autostart_checkbox').attr("checked") == true) 
	{
		$('#autostart').val("1");
	}
	else
	{
		$('#autostart').val("0");
	}
	
	preview();
}

function getSeeqAnswer(query, page)
{
    page = page || 1;
	$("#uploading").show();
	$("#seeq_search_result").hide();

	$.post("seeqsearch.php",
	      { 'action' : 'seeqsearch',
			'query' : query,
			'page' : page
	      },
	      function(data){
				$('#seeq_search_result').html(data);
				$("#uploading").hide();
				$("#seeq_search_result").show();
	      }
	    );
}

function showSeeq()
{
	$('#tagoo_audio_block').attr({
		'style': 'margin-left:50px;margin-right:50px;'
	});

	$('#tagoo_audio_block').html('<div id="sb">'+
		'<form action="" method="post" onsubmit="return false">'+
			'<table cellspacing="0" cellpadding="0">'+
				'<tbody>'+
					'<tr>'+
						'<td>'+
							'<input type="text" name="query" autocomplete="off"/>'+
						'</td>'+
						'<td width="100">'+
							'<input type="submit" class="submit_btn" value="Search!" onclick="getSeeqAnswer(query.value);"/>'+
						'</td>'+
					'</tr>'+
				'</tbody>'+
			'</table>'+
		'</form>'+
		'<div id="seeq_search_result"></div>'+
	'</div>');
}

function showTagoo(tech, search, search_input_tip)
{
	if (search_input_tip) {
		search_input_tip = '<input type="text" value="'+search_input_tip+'" style="text-align:center;color:#C0C0C0;" size="26"/>';
	} else {
		search_input_tip = '';
	}
	$('#tagoo_audio_block').attr({
		'style': 'margin-left:60px;margin-right:55px;'
	});

	$('#tagoo_audio_block').html('<div id="sb">'+
		'<form action="" method="post" onsubmit="return false" >'+
			'<table cellspacing="0" cellpadding="0">'+
				'<tbody>'+
					'<tr align="center" ><td colspan="2">'+
						'<label>'+search+'</label>'+
					'</td></tr>'+
					'<tr width="200px">'+
						'<td width="100">'+							
							'<input type="text" size="26" name="query" id="tagoo_seearch_input" autocomplete="off"/>'+
							search_input_tip +
							'<input type="hidden" value="" name="query_str" id="query_str" />'+
							'<input type="hidden" value="" name="pagenum" id="pagenum" />'+
						'</td>'+
						'<td>'+
							'<input type="submit" class="submit_btn" value="Search!" onclick="getTagooAnswer(query.value, 1);"/>'+
						'</td>'+
					'</tr>'+
				'</tbody>'+
			'</table>'+
		'</form>'+
		'<a href="http://tagoo.ru/ru/" style="text-decoration:none;" target="_blank"><span>' + tech + '</span><img width="53" height="18" src="http://tagoo.ru/images/plogo.png" alt="Tagoo.ru"/></a>'+
		'<div id="tagoo_search_result" align="left"></div>'+
	'</div>');
}

function getTagooAnswer(query, page)
{
    if (page)
    {
        $('#pagenum').val(page);
    }

	$("#uploading").show();
	$("#tagoo_search_result").hide();
	tagoo_init(audio_widget(query));
}

function insertCode(code)
{
	link = $("#link_" + code).val();
	song = $("#song_" + code).val();
	$('#music_url').val(link);
	$('#song_name').val(song);
	file_id = 0;
}


function selectTab(el, type) {
	if (!el) {
		return false;
	}
	
	$('#typetabselector a.current_tab').removeClass('current_tab'); 
	$(el).addClass('current_tab');
	
	$('#tabsearch,#taburl,#tabupload').hide();
	$('#tab'+type).show();
}

function uploadFile(lext) {
	
	$('#uploaderror3').hide();
	$('#uploaderror').hide();
	$('#upload_successfully_finished').hide();
	
	if ( !lext ) {
		lext = 'mp3';
	}

	var done = 0;
	var arr = lext.split('|');
	var flen = document.getElementById('music_upload').value.length;
	var ext = document.getElementById('music_upload').value.substring(flen-3, flen);
	ext = ext.toLowerCase();

	for (i in arr) {
		if (ext == arr[i]) done++;
	}

	if (done>0) {

		$('#uploading_file').show();

		if (window.document.getElementById('mood').value=="insert text") {
			window.document.getElementById('mood').value='';
		}

		var requestDone = false;
		// Create the request object
		var xml = {}

		var input_file_id = new Date().getTime();

		// create form
		var fileId = 'jUploadFile' + input_file_id;
		var form = $('#upl_form');
		var frameId = 'upl_frame';

		var oldElement = $('#music_upload');
		var newElement = $(oldElement).clone();

		$(oldElement).attr('id', fileId);
		$(oldElement).before(newElement);
		$(oldElement).appendTo(form);
		
		if ($('#autostart_checkbox').attr("checked") == true) {
			window.document.getElementById('autostart').value='1';
		} else {
			window.document.getElementById('autostart').value='0';
		}
		

		var uploadCallback = function(isTimeout) {			
			var io = document.getElementById(frameId);
			try 
			{				
				if(io.contentWindow)
				{
					xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
					xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

				}else if(io.contentDocument)
				{
					xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
					xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
			}catch(e)
			{
			}
			if ( xml || isTimeout == "timeout") 
			{				
				requestDone = true;
				var status;
				status = isTimeout != "timeout" ? "success" : "error";
				// Make sure that the request was successful or notmodified
				if ( status != "error" )
				{
					$('#uploading_file').hide();
					// process the data (runs the xml through httpData
					// regardless of callback)
					var data = xml.responseText;
					var error = '';
					try {
						eval( "data = " + data );
					} catch (e) {
						data = {};
						data.error = 'unexpected error';
					}

					if ( data.error ) {
						$('#uploaderror3').html(data.error).show();
					} else {
						
						window.document.getElementById('id').value = data.cid;
						window.document.getElementById('msc_url').value = data.url;
						file_id = data.ident;
						
						preview();
					}
					

				}

				$(io).unbind()

				$(oldElement).remove();
				$('#music_upload').val('');
				if ( !data.error ) {
					$('#upload_successfully_finished').show();
				}

				xml = null

			}
		}

		$(form).submit();

		if(window.attachEvent){
			document.getElementById(frameId).attachEvent('onload', uploadCallback);
		}
		else{
			document.getElementById(frameId).addEventListener('load', uploadCallback, false);
		}


	} else {
		window.document.getElementById('uploaderror').style.display='block';
	} 

	return false;

}


$(document).ready(function(){
	$("#music_url").helpInput();
});