         //Nastroim vyvod informatsii ob AJAX zaprosah
        //Display the information about AJAX  requests
		$(window).ajaxError(function(event, request, settings, error){
			//alert('Request Error ' + error);
                //SMM   alert('Oshibka Zaprosa ' + error);
		});

		//Osnovnoi nabor peremennyh  i konstant (tak skazat' konfiguratsiya)
        //Basic set of variables and contant (say 'configuration')
		var TIME_WIDGET_BAR_SHOW = 2000; //Vremya zaderzhki raboty vypadayuschego menyu

		/*Osuschestvlyaem nachal'nuyu zagruzku WidgetWhell*/
		/*Initial Widget loading is performing here*/
		function getAppId(string){
			return string.replace(/.*(\w{8}-\w{4}-\w{4}-\w{4}-\w{12}).*/, function(string, match){
				return match;
			});
		}
		

		function startWheelWidget(wid)
		{
		    $('body').html(
					'<iframe  style="border:1px solid #aaa;  position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" width="316" height="250" name="msg" scrolling="auto"></iframe>' + '\n' +
		    //'<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" width="316" height="250" name="msg" scrolling="auto"></iframe>'+'\n'+
					'<div id="mediaPanel"></div>'
				);

		    $.ajax({
		        dataType: 'html',
		        global: 'true',
		        type: 'POST',
		        data: { id: wid, flag: 'default' },
		        url: 'proxy.php',
		        success: function(data)
		        {
		            //Proverka na to, chto ne prishli pustye dannye ili dannye nevernogo formata
		            //Check for Empty Data or incorrect Data Format
		            if (data.indexOf('{') == 0)
		            {
		                //Preobrazuem poluchennyi ob'ekt
		                //Changing loaded object
		                widgetWheel = eval("(" + data + ")");
		                //Opredelyaem globalnyi id
		                //Trying to get GLobal ID
		                userId = ID;
		                //Vremya jizni sessii
		                //Session Lifetime
		                sessionLifeTime = 0;

		                var widgetCode = '';
		                if (widgetWheel.media_wheel.category.widget != undefined)
		                {
		                    widgetCode = widgetWheel.media_wheel.category.widget[0].widget_embed_code;
		                    var appId = getAppId(widgetCode);
							appId = appId.replace(/&/g, "%26");
		                    var iframe = document.getElementById('mediaFrame');
		                    iframe.src = 'iframe.php?app_id=' + appId;
		                    loadWidgetWheel(widgetWheel.media_wheel, 'widget', 0, 'widget');
		                }
		                else if (widgetWheel.media_wheel.category.rotations != undefined)
		                {
		                    widgetCode = widgetWheel.media_wheel.category.rotations[0].medias[0].embed_code;
		                    var appId = getAppId(widgetCode);
		                    var iframe = document.getElementById('mediaFrame');
		                    iframe.src = 'iframe.php?app_id=' + appId;
		                    loadWidgetWheel(widgetWheel.media_wheel, 'rotations', 0, 0);
		                }
						else if (widgetWheel.media_wheel.category.videos != undefined)
						{						
							loadWidgetWheel(widgetWheel.media_wheel, 'videos', 0, 'video');
							
							htmlWrite = '' +
											'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
											'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
												'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
													'<head>' + '\n' +
														'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
														'<title>MediaWheel</title>' + '\n' +
													'</head>' + '\n' +
													'<body>' + '\n' +
														'<div id="wraper145269">' + '\n' +
															fixEmbedCode(eval('widgetWheel.media_wheel.category.videos[0].video_embed_code')) + '\n' +
														'</div>' + '\n' +
														'<script>' + '\n' +
													'</body>' + '\n' +
												'</html>' + '\n' +
												'';
							window.frames[0].document.write(htmlWrite);
						}
						else if (widgetWheel.media_wheel.category.image != undefined)
		                {		                    
							loadDefaultImage();
		                }
						else
						{
		                    var iframe = document.getElementById('mediaFrame');
		                    iframe.src = 'iframe.php';
		                    loadWidgetWheel();
		                }
		                setInterval(resizeIframe, 200);
		            }
		            //Esli v poluchennyh dannyh pustaya stroka ili ne vernyi format ob'ekta
		            //If Data are Empty or incorrect Data Format
		            else
		            {
		                //alert("Widget worked incorrectly. Please try again later.")
		            }
		        }
		    });
		};
		/*##############################################################*/
		function loadDefaultImage()
		{
		
			$.ajax({
				dataType: 'html',
				global: 'true',
				type: 'POST',
				data: { id: userId, flag: 'getMedia', mediaName: 'originals' },
				url: 'proxy.php',
				success: function(data)
				{
					//Uznaem nomer elementa
					//find item and album numbers
					itemNum = 0;
					albumNum = 0;

					//Convert received data to JS object
					widgetWheel = eval("(" + data + ")");

					$('body').html(
								'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
					//    '<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
								'<div id="mediaPanel"></div>'
							);
					htmlWrite = '' +
								'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
								'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
									'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
										'<head>' + '\n' +
											'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
											'<title>MediaWheel</title>' + '\n' +
										'</head>' + '\n' +
										'<body>' + '\n' +
											'<div id="wraper145269" width="100%" height="100%">' + '\n' +
												'<img id="bigImage" src="' + widgetWheel.album[albumNum].url[itemNum] + '"/>' + '\n' +
											'</div>' + '\n' +
										'</body>' + '\n' +
									'</html>' + '\n' +
									'';

					window.frames[0].document.write(htmlWrite);

					loadWidgetWheel(widgetWheel, 'album', albumNum, itemNum); //Zapuskaem rabotu widgetWheel

				}
			});


		}
		
		
		
		/*##############################################################*/

		/*Funktsiya vidgeta posle zagruzki pokaza ego paneli*/
		/*After Widget was loaded - this function shows the widget*/
		function loadWidgetWheel(widgetWheel, mediaName, numberPosition, mediaElement, widgetName){
			if (mediaName == 'album' || mediaName == 'videos')
			{
			    isWidgetLoaded = false;
			}
			else
			{
			    isWidgetLoaded = true;
			}
			
			if(mediaName != 'album'){
					document.getElementById('mediaPanel').innerHTML =
						'<style>'+'\n'+
									'<!--'+'\n'+
									'@import url("css/theme-' + THEME +'.css");'+'\n'+
									'-->'+'\n'+
						'</style>'+'\n'+

						'<div id="widget-wrapper">'+'\n'+
							'<div id="widget-bar">'+'\n'+
								'<a id="button-arrow-left"><img src="images/button-arrow-left.gif" width="17" height="19" alt="Go Back" /></a>'+'\n'+
								'<div id="widget-bar-content">'+'\n'+
									'<div id="widget-bar-icon"><img src="images/icon-example-widget.gif" width="16" height="16" alt="Icon Example Widget" /></div>'+'\n'+
									'<div id="widget-bar-content-name">&#60;media name&#62;</div>'+'\n'+
									'<a href="#" id="button-widget-bar-more"><img src="images/button-widget-bar-more.gif" width="13" height="14" alt="Button Widget Bar More" /></a>'+'\n'+
								'</div>'+'\n'+
								'<a id="button-arrow-right"><img src="images/button-arrow-right.gif" width="17" height="19" alt="Go Forward" /></a>'+'\n'+
								'<a href="#" id="button-search" title="Search"></a>'+'\n'+
								'<a href="http://www.mediawheel.com/" target="_blank" id="button-pref" title="Mediawheel.com"></a>'+'\n'+
							'</div><!-- end #widget-bar -->'+'\n'+
						'</div>'+'\n'+
					'<!-- end #widget-wrapper -->';
                    if (widgetWheel)
                    {
                        if (mediaName != "rotations")
                        {
					        $('#widget-bar-content-name').eq(0).text(eval('widgetWheel.category.' + mediaName + '[' + numberPosition +'].' + mediaElement +'_name'));
					    }
					    else
					    {
					        $('#widget-bar-content-name').eq(0).text(eval('widgetWheel.category.' + mediaName + '[' + numberPosition +'].rotation_name'));
					    }
					    setMediaIcon(mediaName);


					    leftRightRotation(widgetWheel, mediaName, numberPosition, mediaElement);
					}
					else
					{
					    $('#widget-bar-content-name').eq(0).text(widgetName);
					    if(mediaName == 'widget')
						    $('#widget-bar-icon img').attr('src','images/icon-widget.png');
					}
					//Menu media
					$('#button-widget-bar-more').click(function(e)
					{
					    e.preventDefault();
					    
					    dropdownMediatype();
					});
					//Knopka poiska
					//Search button
					$('#button-search').click(function(e){
					    e.preventDefault();
						//Proveryaem otkryto li menu
						//Check if menu was opened
						if(typeof openSearchFlag == 'undefined')
							openSearchFlag = false;
						else
							{
								//Esli ne otkryto
								//It was not opened
								if(openSearchFlag == false)
								//Otkryt`
								//Open it
									openSearchFlag = true;
								//Esli otkryto
								//It was opened
								else
								//Zakryt`
								//Close it
									openSearchFlag = false;
							};
						searchMedia(openSearchFlag, false);
					});
				}
			else{
				document.getElementById('mediaPanel').innerHTML =
					'<style>'+'\n'+
								'<!--'+'\n'+
								'@import url("css/theme-' + THEME +'.css");'+'\n'+
								'-->'+'\n'+
					'</style>'+'\n'+

					'<div id="widget-wrapper">'+'\n'+
						'<div id="widget-bar">'+'\n'+
							'<a id="button-arrow-left"><img src="images/button-arrow-left.gif" width="17" height="19" alt="Go Back" /></a>'+'\n'+
							'<div id="widget-bar-content">'+'\n'+
								'<div id="widget-bar-icon"><img src="images/icon-example-widget.gif" width="16" height="16" alt="Icon Example Widget" /></div>'+'\n'+
								'<div id="widget-bar-content-name">&#60;media name&#62;</div>'+'\n'+
								'<a href="#" id="button-widget-bar-more"><img src="images/button-widget-bar-more.gif" width="13" height="14" alt="Button Widget Bar More" /></a>'+'\n'+
							'</div>'+'\n'+
							'<a id="button-arrow-right"><img src="images/button-arrow-right.gif" width="17" height="19" alt="Go Forward" /></a>'+'\n'+
							'<a href="#" id="button-search" title="Search"></a>'+'\n'+
							'<a href="http://www.mediawheel.com/" target="_blank" id="button-pref" title="Mediawheel.com"></a>'+'\n'+
						'</div><!-- end #widget-bar -->'+'\n'+
					'</div>'+'\n'+
				'<!-- end #widget-wrapper -->';
				//$(mediaElement).remove();
				if (widgetWheel)
                {
				    $('#widget-bar-content-name').eq(0).text(eval('widgetWheel.' + mediaName + '[' + numberPosition +'].' + mediaName + '_title'));

				    setMediaIcon(mediaName);


    //				$('#widget-bar-icon img').attr('src','images/icon-example-widget.gif')

				    leftRightRotation(widgetWheel, mediaName, numberPosition, mediaElement);
				}
				else
			    {
			        $('#widget-bar-content-name').eq(0).text(widgetName);
			        if(mediaName == 'widget')
				        $('#widget-bar-icon img').attr('src','images/icon-widget.png');
			    }
			    $('#button-widget-bar-more').click(function(e)
			    {
			        e.preventDefault();
					dropdownMediatype();
				});
				$('#button-search').click(function(e)
				{
				    e.preventDefault();
				//Proveryaem otkryto li menu
					// Check if menu is opened
					if(typeof openSearchFlag == 'undefined')
						openSearchFlag = false;
					else
						{
							if(openSearchFlag == false)
								openSearchFlag = true;
							else
								openSearchFlag = false;
						};
					searchMedia(openSearchFlag, false);
				});
			};
		};
		/*#####################################################################*/


		/* Funktsiya dlya realizatsii klavish' vlevo i vpravo */
		/* Left - Right Buttons Function */
		function leftRightRotation(objRotate, nameMedia, positionBar, itemObj)
		{
		    var iframe = document.getElementById('mediaFrame');
		    if (nameMedia == 'rotations')
		    {
		        rotNum = positionBar;
		        mediaNum = itemObj;
		        $('#button-arrow-left').click(function(e)
		        {
		            e.preventDefault();
		            itemObj--;
		            if (itemObj < 0) itemObj = objRotate.category.rotations[rotNum].medias.length - 1;

		            rotNum = positionBar;
		            mediaNum = itemObj;
		            //itemNum = $(this).get(0).id.substring(4,$(this).get(0).id.length);
		            //Vyesnyayem kod elementa
		            //Generate element's code
		            $('#widget-wrapper').remove();
		            //							$('body').html('<iframe id="mediaFrame" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>');
		            $('body').html(
                    	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
		            //'<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
                    '<div id="mediaPanel"></div>'
                    );
		            htmlWrite = '' +
									'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
									'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
										'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
											'<head>' + '\n' +
												'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
												'<title>MediaWheel</title>' + '\n' +
											'</head>' + '\n' +
											'<body>' + '\n' +
												'<div id="wraper145269">' + '\n' +
													fixEmbedCode(eval('objRotate.category.rotations[rotNum].medias[mediaNum].embed_code')) + '\n' +
												'</div>' + '\n' +
												'<script>' + '\n' +
											'</body>' + '\n' +
										'</html>' + '\n' +
										'';
		            if (objRotate.category.rotations[rotNum].medias[mediaNum].embed_code.indexOf('object') != -1)
		            {
		                window.frames[0].document.write(htmlWrite);
		            }
		            else
		            {

		                //SMM -- this is simplified and corrected code. We need the iframe.php for the correct work on the IE	
		                var widgetCode = objRotate.category.rotations[rotNum].medias[mediaNum].embed_code;
		                var appId = getAppId(widgetCode);
		                var iframe = document.getElementById('mediaFrame');
		                iframe.src = 'iframe.php?app_id=' + appId;
		            }

		            loadWidgetWheel(objRotate, 'rotations', rotNum, mediaNum);
		            setMediaIcon(nameMedia);

		            //						$('#widget-bar-icon img').attr('src', temp[itemObj+'_img']||'images/icon-example-widget.gif');
		            $('#widget-bar-icon img').attr('alt', '');
		        });

		        $('#button-arrow-right').click(function(e)
		        {
		            e.preventDefault();
		            itemObj++;
		            if (itemObj >= objRotate.category.rotations[rotNum].medias.length) itemObj = 0;

		            rotNum = positionBar;
		            mediaNum = itemObj;
		            //itemNum = $(this).get(0).id.substring(4,$(this).get(0).id.length);
		            //Vyesnyayem kod elementa
		            //Generate element's code
		            $('#widget-wrapper').remove();
		            //							$('body').html('<iframe id="mediaFrame" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>');
		            $('body').html(
                    	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
		            //'<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
                    '<div id="mediaPanel"></div>'
                    );
		            htmlWrite = '' +
									'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
									'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
										'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
											'<head>' + '\n' +
												'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
												'<title>MediaWheel</title>' + '\n' +
											'</head>' + '\n' +
											'<body>' + '\n' +
												'<div id="wraper145269">' + '\n' +
													fixEmbedCode(eval('objRotate.category.rotations[rotNum].medias[mediaNum].embed_code')) + '\n' +
												'</div>' + '\n' +
												'<script>' + '\n' +
											'</body>' + '\n' +
										'</html>' + '\n' +
										'';
		            if (objRotate.category.rotations[rotNum].medias[mediaNum].embed_code.indexOf('object') != -1)
		            {
		                window.frames[0].document.write(htmlWrite);
		            }
		            else
		            {

		                //SMM -- this is simplified and corrected code. We need the iframe.php for the correct work on the IE	
		                var widgetCode = objRotate.category.rotations[rotNum].medias[mediaNum].embed_code;
		                var appId = getAppId(widgetCode);
		                var iframe = document.getElementById('mediaFrame');
		                iframe.src = 'iframe.php?app_id=' + appId;
		            }

		            loadWidgetWheel(objRotate, 'rotations', rotNum, mediaNum);
		            setMediaIcon(nameMedia);

		            //						$('#widget-bar-icon img').attr('src', temp[itemObj+'_img']||'images/icon-example-widget.gif');
		            $('#widget-bar-icon img').attr('alt', '');
		        });

		        return;
		    }
		    if (nameMedia != 'album')
		    {
		        /* Nazhatie levoi knopki */
		        /* Left button was clicked */
		        $('#button-arrow-left').click(function(e)
		        {
		            e.preventDefault();
		            positionBar--;
		            if (positionBar < 0) positionBar = objRotate.category[nameMedia].length - 1;
		            if (nameMedia == 'widget')
		            {
		                var newAppId = getAppId(objRotate.category.widget[positionBar].widget_embed_code);
						newAppId = newAppId.replace(/&/g, "%26");
		                iframe.src = 'iframe.php?app_id=' + newAppId;

		                var temp = objRotate.category[nameMedia][positionBar];
		                $('#widget-bar-content-name').eq(0).text(temp[itemObj + '_name']);
		            }
		            else if (nameMedia == 'videos')
		            {
		                $('#widget-wrapper').remove();
		                $('body').html(
                            	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
		                //'<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
	                            '<div id="mediaPanel"></div>'
                            );
		                htmlWrite = '' +
											'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
											'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
												'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
													'<head>' + '\n' +
														'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
														'<title>MediaWheel</title>' + '\n' +
													'</head>' + '\n' +
													'<body>' + '\n' +
														'<div id="wraper145269">' + '\n' +
															fixEmbedCode(eval('objRotate.category.videos[positionBar].video_embed_code')) + '\n' +
														'</div>' + '\n' +
														'<script>' + '\n' +
													'</body>' + '\n' +
												'</html>' + '\n' +
												'';
		                window.frames[0].document.write(htmlWrite);


		                //iframe.src = 'iframe.php?app_id='+appId;
		                //SMM -- may be it is better to add this code right before loadWidgetWheel(...) ???
		                loadWidgetWheel(widgetWheel.media_wheel, 'videos', positionBar, 'video');
		            }
		            setMediaIcon(nameMedia);

		            //						$('#widget-bar-icon img').attr('src', temp[itemObj+'_img']||'images/icon-example-widget.gif');
		            $('#widget-bar-icon img').attr('alt', '');
		        });
		        /*----------------------------------*/

		        //Nazhatie pravoi knopki
		        //Right button was clicked
		        $('#button-arrow-right').click(function(e)
		        {
		            e.preventDefault();
		            positionBar++;
		            if (positionBar >= objRotate.category[nameMedia].length) positionBar = 0;
		            if (nameMedia == 'widget')
		            {
		                var newAppId = getAppId(objRotate.category.widget[positionBar].widget_embed_code);
						newAppId = newAppId.replace(/&/g, "%26");
		                iframe.src = 'iframe.php?app_id=' + newAppId;

		                var temp = objRotate.category[nameMedia][positionBar];
		                $('#widget-bar-content-name').eq(0).text(temp[itemObj + '_name']);
		            }
		            else if (nameMedia == 'videos')
		            {
		                $('#widget-wrapper').remove();
		                $('body').html(
                            	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
		                // '<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
	                            '<div id="mediaPanel"></div>'
                            );
		                htmlWrite = '' +
											'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
											'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
												'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
													'<head>' + '\n' +
														'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
														'<title>MediaWheel</title>' + '\n' +
													'</head>' + '\n' +
													'<body>' + '\n' +
														'<div id="wraper145269">' + '\n' +
															fixEmbedCode(eval('objRotate.category.videos[positionBar].video_embed_code')) + '\n' +
														'</div>' + '\n' +
														'<script>' + '\n' +
													'</body>' + '\n' +
												'</html>' + '\n' +
												'';
		                window.frames[0].document.write(htmlWrite);


		                //iframe.src = 'iframe.php?app_id='+appId;
		                //SMM -- may be it is better to add this code right before loadWidgetWheel(...) ???
		                loadWidgetWheel(widgetWheel.media_wheel, 'videos', positionBar, 'video');
		            }

		            setMediaIcon(nameMedia);

		            //						$('#widget-bar-icon img').attr('src', temp[itemObj+'_img']||'images/icon-example-widget.gif');
		            $('#widget-bar-icon img').attr('alt', '');
		        });
		    }
		    else
		    {
		        /* Nazhatie levoi knopki */
		        /* Left button was clicked */
		        $('#button-arrow-left').click(function(e)
		        {
		            e.preventDefault();
		            itemObj--;
		            if (itemObj < 0) itemObj = objRotate.album[positionBar].url.length - 1;
		            $.ajax({
		                dataType: 'html',
		                global: 'true',
		                type: 'POST',
		                data: { id: userId, flag: 'getMedia', mediaName: 'originals' },
		                url: 'proxy.php',
		                success: function(data)
		                {
		                    //find item and album numbers
		                    itemNum = itemObj;
		                    albumNum = positionBar;

		                    //remove widgetWheel
		                    $('#widget-wrapper').remove();
		                    //Preobrazuem poluchennyi ob'ekt
		                    //Convert received data to JS object
		                    widgetWheel = eval("(" + data + ")");

		                    $('body').html(
                                	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
		                    //     '<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
                                    '<div id="mediaPanel"></div>'
                                );
		                    htmlWrite = '' +
											'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
											'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
												'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
													'<head>' + '\n' +
														'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
														'<title>MediaWheel</title>' + '\n' +
													'</head>' + '\n' +
													'<body>' + '\n' +
														'<div id="wraper145269">' + '\n' +
															'<img id="bigImage" src="' + widgetWheel.album[albumNum].url[itemNum] + '"/>' + '\n' +
														'</div>' + '\n' +
													'</body>' + '\n' +
												'</html>' + '\n' +
												'';

		                    window.frames[0].document.write(htmlWrite);

		                    loadWidgetWheel(widgetWheel, 'album', positionBar, itemObj); //Zapuskaem rabotu widgetWheel

		                }
		            });

		            $('#widget-bar-content-name').eq(0).text(objRotate[nameMedia][positionBar][nameMedia + '_title']);

		            setMediaIcon(nameMedia);

		            //						$('#widget-bar-icon img').attr('src','images/icon-example-widget.gif');
		        });
		        /*----------------------------------*/

		        //Nazhatie pravoi knopki
		        //Right button was clicked
		        $('#button-arrow-right').click(function(e)
		        {
		            e.preventDefault();
		            itemObj++;
		            if (itemObj >= objRotate.album[albumNum].url.length) itemObj = 0;
		            $.ajax({
		                dataType: 'html',
		                global: 'true',
		                type: 'POST',
		                data: { id: userId, flag: 'getMedia', mediaName: 'originals' },
		                url: 'proxy.php',
		                success: function(data)
		                {
		                    //find item and album numbers
		                    itemNum = itemObj;
		                    albumNum = positionBar;

		                    //remove widgetWheel
		                    $('#widget-wrapper').remove();
		                    //Preobrazuem poluchennyi ob'ekt
		                    //Convert received data to JS object
		                    widgetWheel = eval("(" + data + ")");

		                    $('body').html(
                                        	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
		                    //    '<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
	                                        '<div id="mediaPanel"></div>'
                                        );
		                    htmlWrite = '' +
											'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
											'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
												'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
													'<head>' + '\n' +
														'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
														'<title>MediaWheel</title>' + '\n' +
													'</head>' + '\n' +
													'<body>' + '\n' +
														'<div id="wraper145269">' + '\n' +
															'<img id="bigImage" src="' + widgetWheel.album[albumNum].url[itemNum] + '"/>' + '\n' +
														'</div>' + '\n' +
													'</body>' + '\n' +
												'</html>' + '\n' +
												'';

		                    window.frames[0].document.write(htmlWrite);

		                    loadWidgetWheel(widgetWheel, 'album', positionBar, itemObj); //Zapuskaem rabotu widgetWheel

		                }
		            });

		            $('#widget-bar-content-name').eq(0).text(objRotate[nameMedia][positionBar][nameMedia + '_title']);

		            setMediaIcon(nameMedia);


		            //						$('#widget-bar-icon img').attr('src','images/icon-example-widget.gif');

		        });
		    };
		};

        function setMediaIcon(nameMedia)
		{
		    if (nameMedia == 'widget')
		        $('#widget-bar-icon img').attr('src', 'images/icon-widget.png');
		    else if (nameMedia == 'rotations')
		        $('#widget-bar-icon img').attr('src', 'images/icon-rotation.png');
		    else if (nameMedia == 'movie')
		        $('#widget-bar-icon img').attr('src', 'images/icon-movie.png');
		    else if (nameMedia == 'videos')
		        $('#widget-bar-icon img').attr('src', 'images/icon-movie.png');
		    else if (nameMedia == 'album')
		        $('#widget-bar-icon img').attr('src', 'images/icon-flickr.png');
		    else
		        $('#widget-bar-icon img').attr('src', 'images/icon-example-widget.gif');
		}
		/*####################################################################################*/

		/*Funktsiya dobavleniya v telo vidzhita informatsii o razdelah widgetwheel*/
		/*This Fuction adds information about widgetWheel categories into the widget-s */
		function dropdownMediatype(workObj) {
			if(typeof workObj == 'undefined') {
						//Sozdaem tekstovyi variant ob'ekta drop-down, kotoryi nuzhno sozdat'
						//Creating text version of the drop-down. It should be created
						tegLine = '<div class="widget-bar-dropdown">'+'\n'+
										'<div id="nav-dropdown">'+'\n'+
											'<a href="#" id="button-close-sm"></a>'+'\n'+
										'</div>'+'\n'+
										'<div class="dropdown-inner dropdown-media-type">'+'\n'+
											'<ul>'+'\n';
						tegLine += '<li id="mt-widgets" class="media-type-links"><a href="#">Widgets</a></li>'+'\n';
						tegLine += '<li id="mt-rotations" class="media-type-links"><a href="#">Rotations</a></li>'+'\n';
						tegLine += '<li id="mt-photos" class="media-type-links"><a href="#">Photos</a></li>'+'\n';
						tegLine += '<li id="mt-videos" class="media-type-links"><a href="#">Videos</a></li>'+'\n';
						tegLine += '<li id="mt-mwsite" class="media-type-links"><a href="http://www.mediawheel.com/" target="_blank" onclick="onWebPageItemClick()">Mwsite</a></li>'+'\n';
						tegLine += '<li id="mt-search" class="media-type-links"><a href="#">Search</a></li>'+'\n';

						tegLine += '</ul>'+'\n'+
										'</div><!-- .dropdown-inner -->'+'\n'+
										'<div id="dropdown-action">'+'\n'+
										'</div>'+'\n\n'+
										'<!-- .widget-bar-dropdown -->'+'\n'+
									 '</div>';

						
						hideMediaFrame();
						//Dobavlyaem etot ob'ekt v widgetWheel
						//Add this object into the widgetWhee
						$('#widget-wrapper').append(tegLine);

						$('#button-close-sm').click(function(e)
						{
						    e.preventDefault();
						    $('.widget-bar-dropdown').eq(0).remove();
						    showMediaFrame()
						});

						$('.media-type-links').click(function(e)
						{
						    e.preventDefault();
						    //Zapret povtornogo nazhatiya na knopku razdela
						    //No repeated click on category button
						    $(".media-type-links").unbind('click')

						    reqestStr = $(this).get(0).id.replace('mt-', '');
						    //Proverka na imeyuscheesya okonchanie 's'
						    //Check for 's' suffix
						    if (reqestStr.charAt(reqestStr.length - 1).indexOf('s') == 0)
						        reqestStr = reqestStr.substring(0, reqestStr.length - 1);

						    if (reqestStr == 'search')
						    {
						        onSearchClick();
						        return;
						    }

						    if (reqestStr == 'photo')
						    {
						        reqestStr = 'thumbnail';

						    };
						    $.ajax({
						        dataType: 'html',
						        global: 'true',
						        type: 'POST',
						        data: { id: userId, flag: 'getMedia', mediaName: reqestStr },
						        url: 'proxy.php',
						        success: function(data)
						        {
						            //Proverka na to, chto ne prishli pustye dannye ili dannye nevernogo formata
						            //Check for Empty Data or incorrect Data Format
									
						            if (data.indexOf('{') == 0)
						            {
						                //Preobrazuem poluchennyi ob'ekt
						                //Changing the object
						                widgetWheel = eval("(" + data + ")");
						                if (typeof widgetWheel.media_wheel == 'undefined')
						                {
						                    if (typeof widgetWheel.album != 'undefined')
						                    {
						                        $('#nav-dropdown').append('<p><a href="#" id="button-go-back"><img src="images/button-arrow-left.gif" width="16" height="19" alt="Back to categories" /></a> Back to categories</p>' + '\n');
						                        $('#button-go-back').click(function(e)
						                        {
						                            e.preventDefault();
						                            $('.widget-bar-dropdown').eq(0).remove();
						                            dropdownMediatype();
						                        });
						                        dropdownMediatype(widgetWheel);
						                    }
						                    else
						                    {
						                        $('.widget-bar-dropdown').eq(0).remove();
						                        dropdownMediatype();
						                    }
						                }
						                else
						                {
						                    if (widgetWheel.media_wheel != 'false')
						                    {
						                        $('#nav-dropdown').append('<p><a href="#" id="button-go-back"><img src="images/button-arrow-left.gif" width="16" height="19" alt="Back to categories" /></a> Back to categories</p>' + '\n');
						                        $('#button-go-back').click(function(e)
						                        {
						                            e.preventDefault();
						                            $('.widget-bar-dropdown').eq(0).remove();
						                            dropdownMediatype();
						                        });
						                        if (typeof widgetWheel.media_wheel.category.status == 'undefined')
						                            dropdownMediatype(widgetWheel.media_wheel);
												else if (widgetWheel.media_wheel.category.status == 'false')												
													$('.dropdown-inner').eq(0).html('There are no items in this media category');																								
						                        else
						                            $('.dropdown-inner').eq(0).html(widgetWheel.media_wheel.category.status);						                        

						                    }
						                    else
						                    {
						                        //alert('There are no items in this media category');
						                        $('.widget-bar-dropdown').eq(0).remove();
						                        dropdownMediatype();
						                    };
						                };
						            }
						            //Esli v poluchennyh dannyh pustaya stroka ili ne vernyi format ob'ekta
						            //If Data are Empty or incorrect Data Format
						            else
						            {
						                //window.alert("Vidzhet srabotal ne odekvatno, pros'ba povtorit' popytku pozzhe.")
						                //window.alert("Widget worked incorrectly. Please try again later.")
						            }
						        }
						    });

						});
				}
			else
				{
					if(typeof workObj.category != 'undefined')
						{
							if(typeof workObj.category.rotations != 'undefined')
								{
									tegLine = '';
									for(i=0;i<=workObj.category.rotations.length-1;i++)
										{
											tegLine += '<div class="rotation-list-name">'+'\n'+
											'<h3>&#60;'+ workObj.category.rotations[i].rotation_name +'&#62;</h3>'+'\n'+
											'</div>'+'\n'+
											'<ul>';
											for(j=0;j<=workObj.category.rotations[i].medias.length-1;j++)
												{
													tegLine += '<li class="li-odd">'+'\n'+
																		'<div>'+ '\n'+
																			'<input tabindex="0" type="checkbox" name="rotation'+j+'" id="item' + j + '" class="dropdown-checkbox" value="" />'+'\n'+
																			'<label id="' + i + 'item'+ j +'" class="itemReaction">'+workObj.category.rotations[i].medias[j].media_name+'</label>'+'\n'+
																		'</div>'+'\n'+
																	'</li>'+'\n';
												}
											tegLine +='</ul>'+'\n'+
													'</div>'+'\n';
										}
									$('.dropdown-inner').eq(0).remove();
									$('#nav-dropdown').after('<div id="hjk" class="dropdown-inner rotation-list"></div>');
									$('#hjk').get(0).innerHTML = tegLine;
									tegLine = '<a id="button-getmedia" href="#" title="Check the media you want and click Get Media to add it to your wheel.">Get Media</a>' + '\n'+
												 '<a id="button-forward" href="#" title="Check media for your friends and click Forward to add it to their wheel.">Forward</a>' + '\n';
									$('#dropdown-action').html(tegLine);

									//Elsli podvesti k punktu get ili forward
									//If hover over get or forward
									$('#button-getmedia').mouseover(function(){
										$(this).append('<div id="b-getmedia-hover"></div>');
									});
									$('#button-getmedia').mouseout(function(){
										$('#b-getmedia-hover').remove();
									});
									$('#button-forward').mouseover(function(){
										$(this).append('<div id="b-forward-hover"></div>');
									});
									$('#button-forward').mouseout(function(){
										$('#b-forward-hover').remove();
									});
									
									itemClickReaction(3, workObj, 'rotations');
                                    
                                    // copy media to your wheel
									$('#button-getmedia').click(function(e)
									{
									    e.preventDefault();
									    var selectElementsId = [];
								        
								        inputLength = $('input').length;
								        inputObj = $('input');
								        labelObj = $('label');
								        //Skaniruem ih na nalichie id='item...'
								        //Scan those inputs for id='item...'
								        for(i=0;i<inputLength;i++)
									        {
										        if((inputObj.get(i).id.indexOf('item') != -1)&&(inputObj.get(i).checked == true))
											        {
											            var arr = labelObj.get(i).id.split('item');
											            var rotNum = arr[0];
											            var mediaNum = arr[1];
												        selectElementsId.push(workObj.category.rotations[rotNum].medias[mediaNum].media_id);
											        };
									        };
								        var strIDs = selectElementsId.join('-');
								        //Formiruem rezultiruyuschiy massiv
								        //Create resulting array
								        if(selectElementsId.length == 0)
									        //Soobschaem cho nujno vybrat elementy
									        //Report that there is need to select at least 1 item
									        //alert('Vybirite hotyaby 1 element dlya operacii forward');
									        //alert('Please select at least 1 item to copy');											
											copyMedia("");
								        else
									        //Peredaem ego funkcii, kotoraya proizvedet vstavku v akkaunt jelaemyh elementov
									        //Pass it to the function, which will insert that list into the account
									        copyMedia(strIDs);
									});

									//Vybiraem elementy, kotorye napravim pol`zovatelu v akkaunt
									//Select item which should be redirected to the users account
									$('#button-forward').click(function(e)
									{
									    e.preventDefault();
									    var selectElementsId = [];

									    inputLength = $('input').length;
									    inputObj = $('input');
									    labelObj = $('label');
									    //Skaniruem ih na nalichie id='item...'
									    //Scan those inputs for id='item...'
									    for (i = 0; i < inputLength; i++)
									    {
									        if ((inputObj.get(i).id.indexOf('item') != -1) && (inputObj.get(i).checked == true))
									        {
									            var arr = labelObj.get(i).id.split('item');
									            var rotNum = arr[0];
									            var mediaNum = arr[1];
									            selectElementsId.push(workObj.category.rotations[rotNum].medias[mediaNum].media_id);
									        };
									    };
									    var strIDs = selectElementsId.join('-');
									    //Formiruem rezultiruyuschiy massiv
									    //Create resulting array
									    if (selectElementsId.length == 0)
									    //Soobschaem cho nujno vybrat elementy
									    //Report that there is need to select at least 1 item
									    //alert('Vybirite hotyaby 1 element dlya operacii forward');
									        //alert('Please select at least 1 item to copy');
											copyMedia("");
									    else
									    //Peredaem ego funkcii, kotoraya proizvedet vstavku v akkaunt jelaemyh elementov
									    //Pass it to the function, which will insert that list into the account
									        forwardMedia(strIDs);
									});
								}
							else
								{
									if(typeof workObj.category.widget != 'undefined')
										{
											tegLine = '<ul>';
											for(i=0;i<=workObj.category.widget.length-1;i++)
												{
													tegLine += '<li class="li-odd">'+'\n'+
																		'<div>'+ '\n'+
																			'<input tabindex="0" type="checkbox" name="widget'+i+'" id="item'+ i +'" class="dropdown-checkbox" value="" />'+'\n'+
																			'<label id="item'+ i +'" class="itemReaction">'+workObj.category.widget[i].widget_name+'</label>'+'\n'+
																		'</div>'+'\n'+
																	'</li>'+'\n';
												}
											tegLine +='</ul>'+'\n';
											$('.dropdown-inner').eq(0).remove();
											$('#nav-dropdown').after('<div id="hjk" class="dropdown-inner rotation-list"></div>');
											$('#hjk').get(0).innerHTML = tegLine;
											tegLine = '<a id="button-getmedia" href="#" title="Check the media you want and click Get Media to add it to your wheel.">Get Media</a>' + '\n'+
												 '<a id="button-forward" href="#" title="Check media for your friends and click Forward to add it to their wheel.">Forward</a>' + '\n';
											$('#dropdown-action').html(tegLine);

											//Elsli podvesti k punktu get ili forward
											//if mouse is over the Get or Forward buttons
											$('#button-getmedia').mouseover(function(){
												$(this).append('<div id="b-getmedia-hover"></div>');
											});
											$('#button-getmedia').mouseout(function(){
												$('#b-getmedia-hover').remove();
											});
											
											// copy media to your wheel
											$('#button-getmedia').click(function(e)
											{
											    e.preventDefault();
											    var selectElementsId = [];
										        
										        inputLength = $('input').length;
										        inputObj = $('input');
										        //Skaniruem ih na nalichie id='item...'
										        //Scan those inputs for id='item...'
										        for(i=0;i<inputLength;i++)
											        {
												        if((inputObj.get(i).id.indexOf('item') != -1)&&(inputObj.get(i).checked == true))
													        {
														        selectElementsId.push(workObj.category.widget[i].media_id);
													        };
											        };
										        var strIDs = selectElementsId.join('-');
										        //Formiruem rezultiruyuschiy massiv
										        //Create resulting array
										        if(selectElementsId.length == 0)
											        //Soobschaem cho nujno vybrat elementy
											        //Report that there is need to select at least 1 item
											        //alert('Vybirite hotyaby 1 element dlya operacii forward');
											        //alert('Please select at least 1 item to copy');
													copyMedia("");
										        else
											        //Peredaem ego funkcii, kotoraya proizvedet vstavku v akkaunt jelaemyh elementov
											        //Pass it to the function, which will insert that list into the account
											        copyMedia(strIDs);
											});

											$('#button-forward').click(function(e)
											{
											    e.preventDefault();
											    var selectElementsId = [];

											    inputLength = $('input').length;
											    inputObj = $('input');
											    //Skaniruem ih na nalichie id='item...'
											    //Scan those inputs for id='item...'
											    for (i = 0; i < inputLength; i++)
											    {
											        if ((inputObj.get(i).id.indexOf('item') != -1) && (inputObj.get(i).checked == true))
											        {
											            selectElementsId.push(workObj.category.widget[i].media_id);
											        };
											    };
											    var strIDs = selectElementsId.join('-');
											    //Formiruem rezultiruyuschiy massiv
											    //Create resulting array
											    if (selectElementsId.length == 0)
											    //Soobschaem cho nujno vybrat elementy
											    //Report that there is need to select at least 1 item
											    //alert('Vybirite hotyaby 1 element dlya operacii forward');
											        //alert('Please select at least 1 item to copy');
													copyMedia("");
											    else
											    //Peredaem ego funkcii, kotoraya proizvedet vstavku v akkaunt jelaemyh elementov
											    //Pass it to the function, which will insert that list into the account
											        forwardMedia(strIDs);
											});
											
											$('#button-forward').mouseover(function(){
												$(this).append('<div id="b-forward-hover"></div>');
											});
											$('#button-forward').mouseout(function(){
												$('#b-forward-hover').remove();
											});
											itemClickReaction(1, workObj, 'widget', 'widget');
										}
									else
										{
											if(typeof workObj.category.videos != 'undefined')
												{
													tegLine = '<ul>';
													for(i=0;i<=workObj.category.videos.length-1;i++)
														{
															tegLine += '<li class="li-odd">'+'\n'+
																				'<div>'+ '\n'+
																					'<input tabindex="0" type="checkbox" name="widget'+i+'" id="item'+ i +'" class="dropdown-checkbox" value="" />'+'\n'+
																					'<label id="item'+ i +'" class="itemReaction">'+workObj.category.videos[i].video_name+'</label>'+'\n'+
																				'</div>'+'\n'+
																			'</li>'+'\n';
														}
													tegLine +='</ul>'+'\n';
													$('.dropdown-inner').eq(0).remove();
													$('#nav-dropdown').after('<div id="hjk" class="dropdown-inner rotation-list"></div>');
													$('#hjk').get(0).innerHTML = tegLine;
													tegLine = '<a id="button-getmedia" href="#" title="Check the media you want and click Get Media to add it to your wheel.">Get Media</a>' + '\n'+
												 '<a id="button-forward" href="#" title="Check media for your friends and click Forward to add it to their wheel.">Forward</a>' + '\n';
													$('#dropdown-action').html(tegLine);

													//Elsli podvesti k punktu get ili forward
													//if mouse is over the Get or Forward buttons
													$('#button-getmedia').mouseover(function(){
														$(this).append('<div id="b-getmedia-hover"></div>');
													});
													$('#button-getmedia').mouseout(function(){
														$('#b-getmedia-hover').remove();
													});
													
													// copy media to your wheel
											        $('#button-getmedia').click(function(e)
											        {
											            e.preventDefault();
											            var selectElementsId = [];
        										        
										                inputLength = $('input').length;
										                inputObj = $('input');
										                //Skaniruem ih na nalichie id='item...'
										                //Scan those inputs for id='item...'
										                for(i=0;i<inputLength;i++)
											                {
												                if((inputObj.get(i).id.indexOf('item') != -1)&&(inputObj.get(i).checked == true))
													                {
														                selectElementsId.push(workObj.category.videos[i].media_id);
													                };
											                };
										                var strIDs = selectElementsId.join('-');
										                //Formiruem rezultiruyuschiy massiv
										                //Create resulting array
										                if(selectElementsId.length == 0)
											                //Soobschaem cho nujno vybrat elementy
											                //Report that there is need to select at least 1 item
											                //alert('Vybirite hotyaby 1 element dlya operacii forward');
											                //alert('Please select at least 1 item to copy');
															copyMedia("");
															
										                else
											                //Peredaem ego funkcii, kotoraya proizvedet vstavku v akkaunt jelaemyh elementov
											                //Pass it to the function, which will insert that list into the account
											                copyMedia(strIDs);
											        });

											        $('#button-forward').click(function(e)
											        {
											            e.preventDefault();
											            var selectElementsId = [];

											            inputLength = $('input').length;
											            inputObj = $('input');
											            //Skaniruem ih na nalichie id='item...'
											            //Scan those inputs for id='item...'
											            for (i = 0; i < inputLength; i++)
											            {
											                if ((inputObj.get(i).id.indexOf('item') != -1) && (inputObj.get(i).checked == true))
											                {
											                    selectElementsId.push(workObj.category.videos[i].media_id);
											                };
											            };
											            var strIDs = selectElementsId.join('-');
											            //Formiruem rezultiruyuschiy massiv
											            //Create resulting array
											            if (selectElementsId.length == 0)
											            //Soobschaem cho nujno vybrat elementy
											            //Report that there is need to select at least 1 item
											            //alert('Vybirite hotyaby 1 element dlya operacii forward');
											                //alert('Please select at least 1 item to copy');
															copyMedia("");
															
											            else
											            //Peredaem ego funkcii, kotoraya proizvedet vstavku v akkaunt jelaemyh elementov
											            //Pass it to the function, which will insert that list into the account
											                forwardMedia(strIDs);
											        });
													
													$('#button-forward').mouseover(function(){
														$(this).append('<div id="b-forward-hover"></div>');
													});
													$('#button-forward').mouseout(function(){
														$('#b-forward-hover').remove();
													});
													itemClickReaction(0, workObj, 'videos', 'video');
												}
											else
												{
													tegLine = 'Poka ne rabotaet';
													$('.dropdown-inner').eq(0).html(tegLine);
												};
										};
						      };
						}
					else
						{
							if(typeof workObj != 'undefined')
								{
								    tegLine = "";
									for(j=0;j<=workObj.album.length-1;j++)
										{
											tegLine += '<table><tr><td><div id="album' + j + '" class="rotation-list-name"><h3>'+workObj.album[j].album_title+'</h3></div></td></tr>'+'\n';
											tegLine += '<tr><td><ul>'+'\n';
											for(i=0;i<=workObj.album[j].url.length-1;i++)
												{
													tegLine +='<li id="' + j +'item'+ i +'" class="itemReaction">'+'\n'+
																		'<a href="#">'+ '\n'+
																			'<img src="'+workObj.album[j].url[i]+'" width="68" height="56" alt="Dropdown Img Holder" />'+'\n'+
																		'</a>'+'\n'+
																 '</li>'+'\n';
												};
											tegLine +='</ul></td></tr></table>'+'\n';
										}
									$('.dropdown-inner').eq(0).remove();
									$('#nav-dropdown').after('<div id="hjk" class="dropdown-inner dropdown-photos"></div>');
									$('#hjk').get(0).innerHTML = tegLine;
									tegLine = '<a id="button-getmedia" href="#" title="Check the media you want and click Get Media to add it to your wheel.">Get Media</a>' + '\n'+
												 '<a id="button-forward" href="#" title="Check media for your friends and click Forward to add it to their wheel.">Forward</a>' + '\n';
									//$('#dropdown-action').html(tegLine);

									//Elsli podvesti k punktu get ili forward
									//if mouse is over the Get or Forward buttons
									$('#button-getmedia').mouseover(function(){
										$(this).append('<div id="b-getmedia-hover"></div>');
									});
									$('#button-getmedia').mouseout(function(){
										$('#b-getmedia-hover').remove();
									});
									$('#button-forward').mouseover(function(){
										$(this).append('<div id="b-forward-hover"></div>');
									});
									$('#button-forward').mouseout(function(){
										$('#b-forward-hover').remove();
									});
									itemClickReaction(2, workObj)
								}
							else
								{
									//tegLine = 'Poka ne rabotaet';
									tegLine = 'Not working - TBIL';
									$('.dropdown-inner').eq(0).html(tegLine);
								}
						};
				};
		};
		/*##################################################################*/

		/*Funkciya, pokazyvayuschaya vybrannyy element media*/
		/*This function shows selected media item*/
		function itemClickReaction(resultReaction, objectMedia, typeMedia, objectItems)
		{
		    switch (resultReaction)
		    {
		        //Esli vybrannyy element video 
		        //Selected media item is Video 
		        case 0:
		            $('.itemReaction').css('cursor', 'pointer');
		            $('.itemReaction').click(function(e)
		            {
		                e.preventDefault();

		                //Zapret povtornogo nazhatiya element
		                //no repeated click on the item
		                $(".itemReaction").unbind('click');

		                //Uznaem nomer elementa
		                //find item number
		                itemNum = $(this).get(0).id.substring(4, $(this).get(0).id.length);
		                //Vyesnyayem kod elementa
		                //Generate element's code
		                $('#widget-wrapper').remove();
		                //							$('body').html('<iframe id="mediaFrame" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>');
		                $('body').html(
                            	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
		                //    '<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
	                            '<div id="mediaPanel"></div>'
                            );
		                htmlWrite = '' +
											'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
											'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
												'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
													'<head>' + '\n' +
														'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
														'<title>MediaWheel</title>' + '\n' +
													'</head>' + '\n' +
													'<body>' + '\n' +
														'<div id="wraper145269">' + '\n' +
															fixEmbedCode(eval('objectMedia.category.' + typeMedia + '[itemNum].' + objectItems + '_embed_code')) + '\n' +
														'</div>' + '\n' +
														'<script>' + '\n' +
													'</body>' + '\n' +
												'</html>' + '\n' +
												'';
		                window.frames[0].document.write(htmlWrite);

		                //Zadaem reakcii na navedenie myshi na obekt
		                //Setting reaction on the mouse while hover over the object
		                /*window.frames[0].document.onmouseover = function(){
		                tm = setTimeout(function(){
		                loadWidgetWheel(widgetWheel.media_wheel, 'widget', 0, 'widget');//Zapuskaem rabotu widgetWheel
		                },TIME_WIDGET_BAR_SHOW);
		                }
		                window.frames[0].document.onmouseout = function(){
		                clearTimeout(tm);
		                };*/
		                //SMM -- this is simplified and corrected code. We need the iframe.php for the correct work on the IE	
		                var widgetCode = widgetWheel.media_wheel.category.videos[itemNum].video_embed_code;
		                var appId = getAppId(widgetCode);
		                var iframe = document.getElementById('mediaFrame');
		                //iframe.src = 'iframe.php?app_id='+appId;
		                //SMM -- may be it is better to add this code right before loadWidgetWheel(...) ???
		                loadWidgetWheel(widgetWheel.media_wheel, 'videos', itemNum, 'video');

		                //SMM -- this part is for the correct name in the widget-bar	
		                var temp = widgetWheel.media_wheel.category['videos'][itemNum];
		                $('#widget-bar-content-name').eq(0).text(temp['video' + '_name']);

		                setMediaIcon(typeMedia);

		                //						$('#widget-bar-icon img').attr('src', temp['widget'+'_img']||'images/icon-example-widget.gif');
		                $('#widget-bar-icon img').attr('alt', '');

		            });
		            break;
		        //Esli vybrannyy element widget 
		        //Selected media item is Widget 
		        case 1:
		            $('.itemReaction').css('cursor', 'pointer');
		            $('.itemReaction').click(function(e)
		            {
		                e.preventDefault();
		                //Zapret povtornogo nazhatiya element
		                //no repeated clock on the item
		                $(".itemReaction").unbind('click');

		                //Uznaem nomer elementa
		                //find item number
		                itemNum = $(this).get(0).id.substring(4, $(this).get(0).id.length);
		                //Vyesnyayem kod elementa
		                //generate element's code
		                $('#widget-wrapper').remove();
		                //							$('body').html('<iframe id="mediaFrame" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>');
		                $('body').html(
                            	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
		                //    '<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
                                '<div id="mediaPanel"></div>'
                            );
		                htmlWrite = '' +
											'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
											'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
												'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
													'<head>' + '\n' +
														'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
														'<title>MediaWheel</title>' + '\n' +
													'</head>' + '\n' +
													'<body>' + '\n' +
														'<div id="wraper145269">' + '\n' +
															fixEmbedCode(eval('objectMedia.category.' + typeMedia + '[itemNum].' + objectItems + '_embed_code')) + '\n' +
														'</div>' + '\n' +
														'<script>' + '\n' +
													'</body>' + '\n' +
												'</html>' + '\n' +
												'';
		                //window.frames[0].document.write(htmlWrite);


		                //Zadaem reakcii na navedenie myshi na obekt
		                //Setting reaction on the mouse while hover over the object
		                /*window.frames[0].document.onmouseover = function(){
		                tm = setTimeout(function(){
		                loadWidgetWheel(widgetWheel.media_wheel, 'widget', 0, 'widget');//Zapuskaem rabotu widgetWheel
		                },TIME_WIDGET_BAR_SHOW);
		                }
		                window.frames[0].document.onmouseout = function(){
		                clearTimeout(tm);
		                };*/
		                //SMM -- this is simplified and corrected code. We need the iframe.php for the correct work on the IE	
		                var widgetCode = widgetWheel.media_wheel.category.widget[itemNum].widget_embed_code;
		                var appId = getAppId(widgetCode);
						appId = appId.replace(/&/g, "%26");
		                var iframe = document.getElementById('mediaFrame');
		                iframe.src = 'iframe.php?app_id=' + appId;
		                //SMM -- may be it is better to add this code right before loadWidgetWheel(...) ???
		                loadWidgetWheel(widgetWheel.media_wheel, 'widget', itemNum, 'widget');

		                //SMM -- this part is for the correct name in the widget-bar	
		                var temp = widgetWheel.media_wheel.category['widget'][itemNum];
		                $('#widget-bar-content-name').eq(0).text(temp['widget' + '_name']);

		                setMediaIcon(typeMedia);

		                //						$('#widget-bar-icon img').attr('src', temp['widget'+'_img']||'images/icon-example-widget.gif');
		                $('#widget-bar-icon img').attr('alt', '');

		            });
		            break;
		        //Esli vybrannyy element kartinka  
		        //if selected item is an image 
		        case 2:
		            $('.itemReaction').css('cursor', 'pointer');
		            $('.itemReaction').click(function(e)
		            {
		                e.preventDefault();

		                //Zapret povtornogo nazhatiya element
		                //no repeated click on the item
		                $(".itemReaction").unbind('click');

		                //$(this).addClass('selected-photo');
		                idItemElem = $(this).get(0).id;
		                var arr = idItemElem.split('item');

		                //idAlbumElem = $(this).parent().prev().get(0).id;

		                $.ajax({
		                    dataType: 'html',
		                    global: 'true',
		                    type: 'POST',
		                    data: { id: userId, flag: 'getMedia', mediaName: 'originals' },
		                    url: 'proxy.php',
		                    success: function(data)
		                    {
		                        //Uznaem nomer elementa
		                        //find item and album numbers
		                        itemNum = arr[1];
		                        albumNum = arr[0];

		                        //udalyaem widgetWheel
		                        //remove widgetWheel
		                        $('#widget-wrapper').remove();
		                        //Preobrazuem poluchennyi ob'ekt
		                        //Convert received data to JS object
		                        widgetWheel = eval("(" + data + ")");

		                        $('body').html(
                                        	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
		                        //    '<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
	                                        '<div id="mediaPanel"></div>'
                                        );
		                        htmlWrite = '' +
											'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
											'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
												'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
													'<head>' + '\n' +
														'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
														'<title>MediaWheel</title>' + '\n' +
													'</head>' + '\n' +
													'<body>' + '\n' +
														'<div id="wraper145269" width="100%" height="100%">' + '\n' +
															'<img id="bigImage" src="' + widgetWheel.album[albumNum].url[itemNum] + '"/>' + '\n' +
														'</div>' + '\n' +
													'</body>' + '\n' +
												'</html>' + '\n' +
												'';

		                        window.frames[0].document.write(htmlWrite);

		                        loadWidgetWheel(widgetWheel, 'album', albumNum, itemNum); //Zapuskaem rabotu widgetWheel

		                    }
		                });

		            });
		            break;
		        // if rotation item is selected 
		        case 3:
		            $('.itemReaction').css('cursor', 'pointer');
		            $('.itemReaction').click(function(e)
		            {
		                e.preventDefault();
		                //Zapret povtornogo nazhatiya element
		                //no repeated click on the item
		                $(".itemReaction").unbind('click');

		                //find rotation numner and media item number
		                var arr = $(this).get(0).id.split('item');
		                rotNum = arr[0];
		                mediaNum = arr[1];
		                //itemNum = $(this).get(0).id.substring(4,$(this).get(0).id.length);
		                //Vyesnyayem kod elementa
		                //generate element's code
		                $('#widget-wrapper').remove();
		                //							$('body').html('<iframe id="mediaFrame" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>');
		                $('body').html(
                            	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>' + '\n' +
		                //    '<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
	                            '<div id="mediaPanel"></div>'
                            );
		                htmlWrite = '' +
											'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + '\n' +
											'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '\n' +
												'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' + '\n' +
													'<head>' + '\n' +
														'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>' + '\n' +
														'<title>MediaWheel</title>' + '\n' +
													'</head>' + '\n' +
													'<body>' + '\n' +
														'<div id="wraper145269">' + '\n' +
															fixEmbedCode(eval('objectMedia.category.rotations[rotNum].medias[mediaNum].embed_code')) + '\n' +
														'</div>' + '\n' +
														'<script>' + '\n' +
													'</body>' + '\n' +
												'</html>' + '\n' +
												'';
		                if (objectMedia.category.rotations[rotNum].medias[mediaNum].embed_code.indexOf('object') != -1)
		                {
		                    window.frames[0].document.write(htmlWrite);
		                }
		                else
		                {

		                    //SMM -- this is simplified and corrected code. We need the iframe.php for the correct work on the IE	
		                    var widgetCode = objectMedia.category.rotations[rotNum].medias[mediaNum].embed_code;
		                    var appId = getAppId(widgetCode);
		                    var iframe = document.getElementById('mediaFrame');
		                    iframe.src = 'iframe.php?app_id=' + appId;
		                }
		                //SMM -- may be it is better to add this code right before loadWidgetWheel(...) ???
		                loadWidgetWheel(widgetWheel.media_wheel, 'rotations', rotNum, mediaNum);

		                //SMM -- this part is for the correct name in the widget-bar	
		                //var temp = widgetWheel.media_wheel.category['widget'][itemNum];
		                //$('#widget-bar-content-name').eq(0).text(widgetWheel.media_wheel.category.rotations[rotNum].medias[mediaNum].media_name);

		                setMediaIcon(typeMedia);

		                //						$('#widget-bar-icon img').attr('src', temp['widget'+'_img']||'images/icon-example-widget.gif');
		                $('#widget-bar-icon img').attr('alt', '');

		            });
		            break;
		    };
		}

		function searchRequest(searchstr)
        {
            //Posylaem zapros k serveru
            //send request to server
            $.ajax({
                dataType: 'text',
                global: 'true',
                type: 'POST',
                data: { flag: 'serchMedia', searchstring: searchstr, maxresults: 10, pagenum: 1 },
                url: 'proxy.php',
                success: function(data)
                {
                    //vyvodim poluchennuyu informaciyu
                    //display received data
                    searchMedia(true, true, data);
                }
            });
        }

		/* Funkciya poiska */
		/* Search Function */
		function searchMedia(openSearch, resultSearch, searchData, msg) {

			var searchMsg = "";
			if ( msg != undefined )
			{
				searchMsg = '<br/><br/><br/><p style="background-color:white;color:blue;text-align:center;">' + msg + '</p>';
			}
			if((typeof $('#widget-content').get(0) != 'undefined')&&(resultSearch == false))
				{
					$('#widget-content').remove();
					openLoginFlag = true;
				};

			searchHTML = '' +
				'<div id="widget-content">' + '\n'+
					'<div id="widget-content-bluebox" class="widget-content-main">' + '\n'+
						'<div id="widget-content-search">' + '\n'+
							'<a href="#" id="button-close-sm_s"></a>'+'\n'+
							'<form id="search-form" name="searchForm" action="#" method="post">' + '\n'+
								'<div id="search">' + '\n'+
									'<p>Search</p>' + '\n'+
									'<input id="search-field" type="search" name="search" title="search" value="" tabindex="2" />' + '\n'+
								'</div>' + '\n'+
								'<div id="submit">' + '\n'+
									'<input type="image" src="images/button-search-submit.png" alt="Submit" />' + '\n'+
								'</div>' + '\n'+
//								'<div id="close">' + '\n'+
//									'<input type="image" src="images/button-close-sm.png" alt="Close" />' + '\n'+
//								'</div>' + '\n'+
							'</form>' + '\n'+
//							'<p id="advanced"><a href="#">Advanced</a></p>' + '\n'+
							'<div class="group"></div>' + '\n'+
						'</div><!--end #search-form-->' + '\n' + searchMsg
					'</div><!-- #widget-content-bluebox .widget-content-main -->' + '\n'+
//					'<div id="widget-content-links">' + '\n'+
//						'<a href="#" id="content-rec-add" class="content-link-small">Recently added</a>' + '\n'+
//						'<a href="#" id="content-most-pop" class="content-link-small">Most popuar</a>' + '\n'+
//					'</div>' + '\n'+
							'<div id="widget-content-links">'+'\n'+
								'<a href="http://www.mediawheel.com/" id="content-register" target="_blank">Get your own MediaWheel. Click here to register.</a>'+'\n'+
							'</div>'+'\n'+
				'</div>';


			if (resultSearch == false)
				{
					if (openSearch == false)
						{
						    $('#widget-bar-dropdown').remove();
						    hideMediaFrame();
							$('#widget-wrapper').append(searchHTML);
							$("#submit input").replaceWith('<img src="images/button-search-submit.png" width="23" height="18" alt="Submit" />');
							$("#submit img").css('cursor','pointer');
							//Function sends message for serch
							$("#submit img").click( function(){

							//Zapret povtornogo nazhatiya na knopku poiska
								//no repeated click on the search button
								$("#submit img").unbind('click');

								//Proveryaem chto stroka v pole poiska ne pustaya
								//check for the search string is empty
								if(document.searchForm.search.value != '')
									searchRequest(document.searchForm.search.value);
									//Esli pole poiska pustoe, to soobschaem eto pol`zovatelyu
								//if the search field is empty show the alert to the user 
								else
									{
										openSerachFlag = true;
										searchMedia(false,false, "", "Enter search string");
									};
							});
							
							// starts search process if enter is pressed
							$("#search input").keypress( function(e){
								if (e.which == 13) {
								    e.preventDefault();
								    e.stopPropagation();
								    //Zapret povtornogo nazhatiya na knopku poiska
								    //no repeated click on the search button
								    $("#search input").unbind('keypress');

								    //Proveryaem chto stroka v pole poiska ne pustaya
								    //check for the search string is empty
								    if(document.searchForm.search.value != '')
								        searchRequest(document.searchForm.search.value);
									    //Esli pole poiska pustoe, to soobschaem eto pol`zovatelyu
									    //if the search field is empty show the alert to the user 
								    else
									    {
										    openSerachFlag = true;
										    searchMedia(false,false, "", "Enter search string");
									    };
								 }
							});
							
						}
					else
					{
						$('#widget-content').remove();
						showMediaFrame();
					}
				}
			else
				{

					var searchInfo = document.searchForm.search.value;
					//Esli poiskovaya informaciya, poluchennaya ot servera ne sodergit ni odnogo simvola, znachit my nichego ne nashli po zaprosu
					//if search data received from server is empty it means we found nothing for our request
					if (searchData == '')
						{
							document.searchForm.search.value = '';
							openSerachFlag = true;
							searchMedia(false,false, "", "No found result, enter new search string");
						}
						//Inache my preobrazuem dannye i vyvodim ih
					//otherwise convert data and display it
					else
						 {
							//Sozdaem ob`ekt JSON notacii
							//Creating JSON object
							if(searchData.indexOf('{') == 0)
								{
									dataElem = eval("(" + searchData + ")");
									$('#widget-content').remove();
									searchResultHTML = ''+'\n'+
																'<div id="widget-content">'+'\n'+
																	'<div class="widget-content-main">'+'\n'+
																		'<div id="search-bar">'+'\n'+
																			'<div id="widget-content-search">'+'\n'+
																			    '<a href="#" id="button-close-sm_s"></a>'+'\n'+
																				'<form id="search-form" name="searchForm" action="#" method="#">'+'\n'+
																					'<div id="search">'+'\n'+
																						'<p>Search</p>'+'\n'+
																						'<input id="search-field" type="search" name="search" title="search" value="" tabindex="2" />'+'\n'+
																					'</div>'+'\n'+
																					'<div id="submit">'+'\n'+
																						'<input type="image" src="images/button-search-submit.png" alt="Submit" />'+'\n'+
																					'</div>'+'\n'+
																				'</form>'+'\n'+
																				//'<p id="advanced"><a href="#">Advanced</a></p>'+'\n'+
																				'<div class="group"></div>'+'\n'+
																			'</div><!--end #search-form-->'+'\n'+
																		'</div><!-- end #search-bar -->'+'\n'+
																		'<div class="widget-content-display">'+'\n'+
																			'<div id="category_widget_list">'+'\n'+
																				'<ul>'+'\n'+
																				'';

									textObj = document.createTextNode('');
									//Preobrazuem dannye iz obekta dataELEM v HTML kod
									//convert data from the dataELEM object to HTML code
									for (i=0;i<dataElem.medias.length;i++) {
										textObj = dataElem.medias[i].embed_code;
										textObj = textObj.replace('<','&lt;');
										textObj = textObj.replace('>','&gt;');
										searchResultHTML +=''+
													'<li>'+
														'<img src="' + dataElem.medias[i].media_img +'"width="94" height="94" alt="Widget Icon" />'+'\n'+
														'<div>'+'\n'+
															'<h3><a href="#" id="searchItem'+ i +'">'+dataElem.medias[i].media_name+'</a></h3>'+'\n'+
															'<p class="widget_author">Author: <span>Author name</span></p>'+'\n'+
															'<p class="widget_description">'+""+'</p>'+'\n'+
															//'<input id="searchItemButton'+ i +'" type="image" src="images/button_get_widget.gif" width="108" height="18" class="submit" />'+
														'</div>'+'\n'+
														'<div class="group"></div>'+'\n'+
													'</li>'+'\n'+
													'';
													
									};
									searchResultHTML += ''+'\n'+
																	'</ul>'+'\n'+
																'</div>'+'\n'+
															'</div><!-- .widget-content-display -->'+'\n'+
														'</div><!-- #widget-content-bluebox .widget-content-main -->'+'\n'+
														'<div id="widget-content-links">'+'\n'+
															'<a href="http://www.mediawheel.com/" id="content-register" target="_blank">Get your own MediaWheel. Click here to register.</a>'+'\n'+
														'</div>'+'\n'+
													'</div>'+'\n';
									hideMediaFrame();
									//Vstavlyaem poluchennye danney v kod paneli poiska
									//insert received data to the search panel code
									$('#widget-wrapper').append(searchResultHTML);
									
									for (i=0;i<dataElem.medias.length;i++) {
									    $("#searchItem" + i).click(function(e)
									    {
									        e.preventDefault();
									        itemNum = $(this).get(0).id.substring(10, $(this).get(0).id.length);

									        onSearchItemClick(dataElem, itemNum);
									    });
//										$("#searchItemButton"+ i).click(function()
//										{
//										    itemNum = $(this).get(0).id.substring(16,$(this).get(0).id.length);
//										
//										    onSearchItemClick(dataElem, itemNum);
//										});
									
									}
									
									$("#submit input").replaceWith('<img src="images/button-search-submit.png" width="23" height="18" alt="Submit" />');
									$("#submit img").css('cursor','pointer');
									document.searchForm.search.value = searchInfo;
									$("#submit img").click( function(){

									//Zapret povtornogo nazhatiya na knopku poiska
										//no repeated click on the search button
										$("#submit img").unbind('click');

										//Proveryaem chto stroka v pole poiska ne pustaya
										//check for the search string is empty
										if(document.searchForm.search.value != '')
										    searchRequest(document.searchForm.search.value);
											//Esli pole poiska pustoe, to soobschaem eto pol`zovatelyu
											//if the search field is empty show the alert to the user 										
									});
									
									// starts search process if enter is pressed
							        $("#search input").keypress( function(e){
								        if (e.which == 13) {
								            e.preventDefault();
								            e.stopPropagation();
								            //Zapret povtornogo nazhatiya na knopku poiska
								            //no repeated click on the search button
								            $("#search input").unbind('keypress');

								            //Proveryaem chto stroka v pole poiska ne pustaya
								            //check for the search string is empty
								            if(document.searchForm.search.value != '')
								                searchRequest(document.searchForm.search.value);
									            //Esli pole poiska pustoe, to soobschaem eto pol`zovatelyu
									            //if the search field is empty show the alert to the user
								            else
									            {
										            //alert('Enter serch string');
										            openSerachFlag = true;										            
													searchMedia(false,false, "", "Enter search string");
									            };
								         }
							        });							
								}
							else {
								//alert('Ne vernyy format zapisi')
								openSerachFlag = true;
								searchMedia(false,false);
								
								};
						 };

				};

				$('#button-close-sm_s').click(function(e)
				{
				    e.preventDefault();
				    showMediaFrame();
				    $('#widget-content').remove();
				    openLoginFlag = true;

				    if (typeof openSearchFlag == 'undefined')
				        openSearchFlag = true;
				    else
				    {
				        openSearchFlag = true;
				    };
				});

		};
		/*############################################################################*/

		/* Funkciya dlya otkrytiya menu registracii */
		//function that opens registration menu
		function loginMenu(openLogin, elementsToMove) {
			if((typeof $('#widget-content').get(0) != 'undefined')&&(openLogin == false))
				{
					$('#widget-content').remove();
					openSearchFlag = true;
				};

			if(openLogin == false)
				{
					loginHTML = ''+
						'<div id="widget-content">'+'\n'+
							'<div id="widget-content-signin" class="widget-content-main">' + '\n' +
							    '<a href="#" id="button-close-sm_login"></a>' + '\n' +
								'<div id="login-form">'+'\n'+
									'<h4>Please sign in</h4>'+'\n'+
									'<div id="login" name="login">' + '\n' +
										'<div id="email">'+'\n'+
											'<label for="email-field" class="overlabel">Email Address</label>'+'\n'+
											'<input id="email-field" type="text" name="email" title="Email address" value="" tabindex="1" />'+'\n'+
										'</div>'+'\n'+
										'<div id="password">'+'\n'+
											'<label for="password-field" class="overlabel">Password</label>'+'\n'+
											'<input id="password-field" type="password" name="password" title="password" value="" tabindex="2" />'+'\n'+
										'</div>'+'\n'+
										'<div id="submit">'+'\n'+
											'<input type="image" src="images/button-login.gif" alt="Login" tabindex="3"/>' + '\n' +
										'</div>'+'\n'+
									'</div>' + '\n' +
									//'<a href="#" id="forgot-password">Forgot password?</a>'+'\n'+
									//'<p><a href="http://www.mediawheel.com/">Forgot password?</a></p>'+'\n'+
									'<div class="group"></div>'+'\n'+
								'</div><!--end #login_form-->'+'\n'+
							'</div><!-- #widget-content-signin .widget-content-main -->'+'\n'+
							'<div id="widget-content-links">'+'\n'+
								'<a href="http://www.mediawheel.com/" target="_blank" id="content-register">Get your own MediaWheel. Click here to register.</a>'+'\n'+
							'</div>'+'\n'+
						'</div>';
						hideMediaFrame();
						$('#widget-wrapper').append(loginHTML);
						openLoginFlag = false;
						$('#email-field').focus(function(){ $(this).prev().remove(); });
						$('#password-field').focus(function(){ $(this).prev().remove(); });
						$('#button-close-sm_login').click(function(e)
						{
						    e.preventDefault();
						    showMediaFrame();
						    $('#widget-content').remove();
						    openLoginFlag = true;
						    //Esli zadan intervel, ubrat` ego
						    //if an interval is set remove it
						    if (typeof forwardInterv != 'undefined')
						    {
						        clearInterval(forwardInterv);
						        forwardInterv = undefined;
						    };

						    if (typeof copyInterv != 'undefined')
						    {
						        clearInterval(copyInterv);
						        copyInterv = undefined;
						    };
						    
						});
						//$("#submit input").replaceWith('<img src="images/button-login.gif" width="69" height="22" alt="Submit" />');
						$('#submit input').eq(0).css('cursor', 'pointer');
						$('#submit input').eq(0).click(function()
						{
						    if ($('#email-field').get(0).value == '' || $('#password-field').get(0).value == '')
						    {
						        alert('Please fill in email and password fields.');
						        return;
						    }
						    //Zapret povtornogo nazhatiya na knopku login
						    //no repeated click on login button
						    $("#submit input").unbind('click');

						    var emailValue = $('#email-field').get(0).value;
						    var passwordValue = $('#password-field').get(0).value;

						    loginRequest(emailValue, passwordValue, openLogin);
						});


						$('#password-field').keypress(function(e)
						{
						    if (e.which == 13)
						    {
						        if ($('#email-field').get(0).value == '' || $('#password-field').get(0).value == '')
						        {
						            alert('Please fill in email and password fields.');
						            return;
						        }
						        //Zapret povtornogo nazhatiya na knopku login
						        //no repeated click on login button
						        $('#password-field').unbind('keypress');

						        var emailValue = $('#email-field').get(0).value;
						        var passwordValue = $('#password-field').get(0).value;

						        loginRequest(emailValue, passwordValue, openLogin);
						    }
						});
				}
			else
				{
					$('#widget-content').remove();
				};
		};

		// performs a login request to server
		function loginRequest(email, pass, openLogin)
        {
            //Posylaem zapros k serveru
            //send request to server
            $.ajax({
                dataType: 'text',
                global: 'true',
                type: 'POST',
                data: { flag: 'login', emailAddress: email, password: pass },
                url: 'proxy.php',
                success: function(data)
                {
                    $('#widget-content').remove();
                    loginMenu(openLogin);

                    //Esli otvet ot servera pustoy
                    //if response is empty show message
                    if (data == '')
                    {
                        alert('Try next time');
                        //alert('Poprobuyte v dugoy raz');
                    }
                    //Inache my preobrazuem dannye i vyvodim ih
                    //otherwise convert data and display it
                    else
                    {
                        //Sozdaem ob`ekt JSON notacii
                        //create JS object
                        if (data.indexOf('{') == 0)
                        {
                            loginObj = eval('(' + data + ')');
                            if (typeof loginObj.message != 'undefined')
                                alert(loginObj.message)
                            else
                            {
                                if (typeof loginObj.auth_token != 'undefined')
                                    userLoginId = loginObj.auth_token;
                                sessionLifeTime = 86400;
                                //																		if(typeof loginObj.session_lifetime != 'undefined')
                                //																			sessionLifeTime = loginObj.session_lifetime;
                                eMailLogin = $('#email-field').get(0).value;
                                $('#widget-content').remove();
                                openLoginFlag = true;
                            };
                        };
                    };

                }
            });
        }

	
		
		/* Functiya dlya kopirovaniya media na akkaunt*/
		//function that copies media to some account
		function forwardMedia(itemsIDs)
		{		    
			if (typeof $('#widget-content').get(0) != 'undefined')
			{
				$('#widget-content').remove();
			};

			$('.widget-bar-dropdown').eq(0).remove();

			panelHTML = '' +
					'<div id="widget-content">' + '\n' +
						'<div id="widget-content-signin" class="widget-content-main">' + '\n' +
							'<a href="#" id="button-close-sm_login"></a>' + '\n' +
							'<div id="login-form">' + '\n' +
								'<h4 id="forwardText">Please enter user email</h4>' + '\n' +
								'<div id="login" name="login">' + '\n' +
									'<div id="email">' + '\n' +
										'<label for="email-field" class="overlabel">Recipient Address</label>' + '\n' +
										'<input id="email-field" type="text" name="email" title="Email address" value="" tabindex="1" />' + '\n' +
									'</div>' + '\n' +
									'<div id="email">' + '\n' +
										'<label for="sender-field" class="overlabel">Sender Address</label>' + '\n' +
										'<input id="sender-field" type="text" name="sender" title="Sender address" value="" tabindex="2" />' + '\n' +
									'</div>' + '\n' +
									'<div id="email">' + '\n' +
										'<label for="fwdmessage-field" class="overlabel">Message</label>' + '\n' +
										'<input id="fwdmessage-field" type="text" name="fwdmessage" title="Message" value="" tabindex="2" />' + '\n' +
									'</div>' + '\n' +
									'<div id="submit">' + '\n' +
										'<input type="image" src="images/button-forward-large.gif" alt="Forward" tabindex="3"/>' + '\n' +
									'</div>' + '\n' +
								'</div>' + '\n' +
								'<div class="group"></div>' + '\n' +
								'<p id="msg"></p>' + '\n' +
							'</div><!--end #login_form-->' + '\n' +
						'</div><!-- #widget-content-signin .widget-content-main -->' + '\n' +
						'<div id="widget-content-links">' + '\n' +
							'<a href="http://www.mediawheel.com/" target="_blank" id="content-register">Get your own MediaWheel. Click here to register.</a>' + '\n' +
						'</div>' + '\n' +
					'</div>';
									
			hideMediaFrame();
			$('#widget-wrapper').append(panelHTML);

			$('#email-field').focus(function() { $(this).prev().remove(); });
			$('#sender-field').focus(function() { $(this).prev().remove(); });
			$('#fwdmessage-field').focus(function() { $(this).prev().remove(); });

			$('#button-close-sm_login').click(function(e)
			{
				e.preventDefault();
				showMediaFrame();
				$('#widget-content').remove();
			});

			//$("#submit input").replaceWith('<img src="images/button-forward-large.gif" width="90" height="22" alt="Forward" />');
			$('#submit input').eq(0).css('cursor', 'pointer');
			$('#submit input').eq(0).click(function()
			{
				if ($('#email-field').get(0).value == '' )
				{
					$('#msg').html('Please fill in both email fields.');
					return;
				}
				
				if ($('#sender-field').get(0).value == '' )
				{
					$('#msg').html('Please fill in both email fields.');
					return;
				}
				//Zapret povtornogo nazhatiya na knopku login
				//no repeated click on login button
				$("#submit input").unbind('click');

				var email = $('#email-field').get(0).value;
				var sender = $('#sender-field').get(0).value;
				var fwdmessage = $('#fwdmessage-field').get(0).value;

				forwardRequest(itemsIDs, email, sender, fwdmessage);

				$('.widget-bar-dropdown').eq(0).remove();
				$('#widget-content').remove();
				//showMediaFrame();
			});
		
		};

        // performs forward request
		function forwardRequest(itemsIDs, email, sender, fwdmessage)
        {
			$.ajax({
                dataType: 'text',
                global: 'true',
                type: 'POST',
                data: { flag: 'forwardMedia', mediaIDs: itemsIDs, recipientEmail: email, senderEmail : sender, forwardMessage : fwdmessage },
                url: 'proxy.php',
                success: function(data)
                {

					
					var objData = eval(data);
                    var reasons = [];

                    for (var i = 0; i < objData.length; i++)
                    {
                        if (objData[i].success == 'false')
                        {
                            reasons.push(objData[i].message);
                        }
                    }					
					
					var resStr = "";
					if (reasons.length == 0)
                    {
                        resStr = 'Operation succeeded. Items were successfully forwarded';
                    }
                    else
                    {
                        var resStr = reasons.join('\n- ');
                        resStr = '\n- ' + resStr;
                        resStr = 'Operation failed. Reasons:' + resStr;
                    }
					
					panelHTML = '' +
					    '<div id="widget-content">' + '\n' +
						    '<div id="widget-content-signin" class="widget-content-main">' + '\n' +
							'<a href="#" id="button-close-sm_login"></a>' + '\n' +
							'<div id="alert-form">' + '\n' +
							resStr +	
							'<br/><center><a href="#" id="okbutton"><img src="images/button-ok.gif"></img></a></center>' + 
							'</div><!--end #login_form-->' + '\n' +
						    '</div><!-- #widget-content-signin .widget-content-main -->' + '\n' +
						    '<div id="widget-content-links">' + '\n' +
							    '<a href="http://www.mediawheel.com/" target="_blank" id="content-register">Get your own MediaWheel. Click here to register.</a>' + '\n' +
						    '</div>' + '\n' +
					    '</div>';						
						
					$('#widget-wrapper').append(panelHTML);
					//zzz(10000);
					
					$('#button-close-sm_login').click(function(e)
					{
						e.preventDefault();
						showMediaFrame();
							$('.widget-bar-dropdown').eq(0).remove();
							$('#widget-content').remove();
					});
					
					$('#okbutton').click(function(e)
					{
						e.preventDefault();
						showMediaFrame();
							$('.widget-bar-dropdown').eq(0).remove();
							$('#widget-content').remove();
					});
					
					
                }
            });
        }

		function onSearchClick()
		{
		    $('.widget-bar-dropdown').eq(0).remove();
            //Proveryaem otkryto li menu
			//Check if menu was opened
			if(typeof openSearchFlag == 'undefined')
				openSearchFlag = false;
			else
				{
					$('mediaFrame').show();
						openSearchFlag = false;
				};
			searchMedia(false, false);
        };
        
        function onWebPageItemClick()
        {
            $('.widget-bar-dropdown').eq(0).remove();
            showMediaFrame();
        };
        
        //function that handles search item click
        function onSearchItemClick(data, itemNum)
        {
            $('#widget-wrapper').remove();
            //							$('body').html('<iframe id="mediaFrame" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>');
            $('body').html(
            	'<iframe  style="border:1px solid #aaa; position:absolute; top:32px; left:0px;" id="mediaFrame" scrolling="auto" frameborder="0" name="msg" width="320" height="320" scrolling="auto"></iframe>'+'\n'+
            //'<iframe  style="border:1px solid #aaa;" id="mediaFrame" frameborder="0" name="msg" width="320" height="265" scrolling="auto"></iframe>'+'\n'+
            '<div id="mediaPanel"></div>'
            );
			htmlWrite = ''+
							'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'+'\n'+
							'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'+'\n'+
								'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'+'\n'+
									'<head>'+'\n'+
										'<meta http-equiv="Content-Type" content="text/html; charset=utf-1251"/>'+'\n'+
										'<title>MediaWheel</title>'+'\n'+
									'</head>'+'\n'+
									'<body>'+'\n'+
										'<div id="wraper145269">'+'\n'+
											fixEmbedCode(eval('data.medias[itemNum].embed_code'))+'\n'+
										'</div>'+'\n'+
										'<script>'+'\n'+
									'</body>'+'\n'+
								'</html>'+'\n'+
								'';
			if (data.medias[itemNum].embed_code.indexOf('object') != -1)
			{
			    window.frames[0].document.write(htmlWrite);
			}
			else
			{	
				var widgetCode = data.medias[itemNum].embed_code;
			    var appId = getAppId(widgetCode);
			    if (appId != widgetCode)
			    {
			        var iframe = document.getElementById('mediaFrame');
			        iframe.src = 'iframe.php?app_id='+appId;
			    }
			    else
			    {			        
			        var iframe = document.getElementById('mediaFrame');
			        iframe.src = 'iframe2.php?code=' + htmlWrite.replace(/"/gi, '%22');
			    }
			    
			}
	        
	        loadWidgetWheel(null, 'widget', 0, 'widget', data.medias[itemNum].media_name);
	        
	        if(typeof openSearchFlag == 'undefined')
				openSearchFlag = true;
			else
				{
						openSearchFlag = true;
				};
        };
        
        //function for iframe resizing
        function resizeIframe()
        {
            var iframe = document.getElementById('mediaFrame');
            if (iframe && iframe.contentWindow.document.getElementsByTagName('body')[0])
            {
                var body = iframe.contentWindow.document.getElementsByTagName('body')[0];
                if (body)
                {
                    body.style.margin = "0px";
                    if (network == 'igoogle')
                    {
                        try
                        {
                            maxWidth = this.parent.frames[0].document.body.offsetWidth - 5;
                        }
                        catch (exc)
                        {
                            maxWidth = this.frames.document.body.offsetWidth - 5;
                        }
                    }
                    var obj = body.getElementsByTagName('object')[0];
                    var embed = body.getElementsByTagName('embed')[0];
                    var image = body.getElementsByTagName('img')[0];                    
                    var script = body.getElementsByTagName('script')[0];                    
                    if (obj)
                    {
                        if (body.offsetHeight < maxHeight && obj.offsetWidth < maxWidth)
                        {
                            iframe.height = body.offsetHeight;
                            iframe.width = obj.offsetWidth;
                        }
                        else
                        {
                            iframe.height = body.offsetHeight + 20 < maxHeight ? body.offsetHeight + 20 : maxHeight;
                            iframe.width = obj.offsetWidth + 20 < maxWidth ? obj.offsetWidth + 20 : maxWidth;
                        }
                    }
                    else if (embed)
                    {
                        if (body.offsetHeight < maxHeight && embed.offsetWidth < maxWidth)
                        {
                            iframe.height = body.offsetHeight;
                            iframe.width = embed.offsetWidth;
                        }
                        else
                        {
                            iframe.height = body.offsetHeight + 20 < maxHeight ? body.offsetHeight + 20 : maxHeight;
                            iframe.width = embed.offsetWidth + 20 < maxWidth ? embed.offsetWidth + 20 : maxWidth;
                        }
                    }
                    else if (script && image)
                    {
                            iframe.height = maxHeight;
                            iframe.width = maxWidth;
                    }
                    else if (image)
                    {
                        if (body.offsetHeight < maxHeight && image.offsetWidth < maxWidth)
                        {
                            iframe.height = body.offsetHeight;
                            iframe.width = image.offsetWidth;
                        }
                        else
                        {
                            if (image.height > maxHeight)
                            {
                                var k = image.height / maxHeight;
                                iframe.height = maxHeight;
                                image.height /= k;
                            }
                            if (image.width > maxWidth)
                            {
                                var k = image.width / maxWidth;
                                iframe.width = maxWidth;
                                image.width /= k;
                            }
                            image.height -= 5;
                            image.width -= 5;
                        }
                    }
                }
            }
        };
        
        // function that solves flash overlapping problem if flash movie is loaded
        function fixEmbedCode(code)
        {
            code = code.replace('<embed', '<embed wmode="opaque"');
            code = code.replace('<EMBED', '<EMBED wmode="opaque"');
            return code;
        };

        //function that copies media to your account
        function copyMedia(itemsIDs)
        {
			if(itemsIDs == "")
			{
				$('.widget-bar-dropdown').eq(0).remove();
			    showMediaFrame();
			}
			else
			{
				if(sessionLifeTime == 0 || userLoginId == 'undefined')
				{
					$('.widget-bar-dropdown').eq(0).remove();
					loginMenu(false);
					copyInterv = setInterval(function(){if(sessionLifeTime != 0){ clearInterval(copyInterv); copyMedia(itemsIDs); };},1000);
				}
				else
				{
					$.ajax({
						dataType: 'text',
						global: 'true',
						type: 'POST',
						data: { id: userLoginId, flag: 'copyMedia', mediaIDs: itemsIDs },
						url: 'proxy.php',
						success: function(data)
						{
							var objData = eval(data);
							var reasons = [];

							for (var i = 0; i < objData.length; i++)
							{
								if (objData[i].success == 'false')
								{
									reasons.push(objData[i].message);
								}
							}

							if (reasons.length == 0)
							{
								//alert('Operation succeeded. Items were successfully added');
							}
							else
							{
								var resStr = reasons.join('\n- ');
								resStr = '\n- ' + resStr;
								alert('Operation failed. Reasons:' + resStr);
							}

						}
					});
					$('.widget-bar-dropdown').eq(0).remove();
					showMediaFrame();
				};
			}
        };
		
        
        // hides media frame
        function hideMediaFrame()
        {
            if (isWidgetLoaded)
            {
                $('#mediaFrame').hide();
            }    
        };
        
        //shows media frame
        function showMediaFrame()
        {
            $('#mediaFrame').show();
        };