
function js_array_to_php_array (a)
// This converts a javascript array to a string in PHP serialized format.
// This is useful for passing arrays to PHP. On the PHP side you can 
// unserialize this string from a cookie or request variable. For example,
// assuming you used javascript to set a cookie called "php_array"
// to the value of a javascript array then you can restore the cookie 
// from PHP like this:
//    <?php
//    session_start();
//    $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
//    print_r ($my_array);
//    ?>
// This automatically converts both keys and values to strings.
// The return string is not URL escaped, so you must call the
// Javascript "escape()" function before you pass this string to PHP.
{
    var a_php = "";
    var total = 0;
    for (var key in a)
    {
        ++ total;
        a_php = a_php + "s:" +
                String(key).length + ":\"" + String(key) + "\";s:" +
                String(a[key]).length + ":\"" + String(a[key]) + "\";";
    }
    a_php = "a:" + total + ":{" + a_php + "}";
    return a_php;
}

// AJAX Stuff #####################################################################

	// make asynchronous HTTP request using the XMLHttpRequest object
	function getComments(pMedia_id, pPage, pUserId, pElementId, pResourceType)
	{	
		var Ajax = new AjaxRequest();

		if( Ajax.mRequest )
		{
			Ajax.mId = pMedia_id;
			
			Ajax.mPage = pPage;
			
			Ajax.mUserId = pUserId; 
			
			Ajax.mElementId = pElementId;
			
			Ajax.mpResourceType = pResourceType;
			
			var is_admin = document.getElementById('user_is_admin').value;
			
			Ajax.mElementIsAdmin = is_admin;
			
			Ajax.addEventListener( REQ_COMPLETE, handleServerResponse );
			
			//To make it safe, serialize the JS array to PHP array
			var param = Array(5);
			param[0] = pMedia_id;
			param[1] = pPage;
			param[2] = pUserId;
			param[3] = is_admin;
			param[4] = pResourceType;
			
			php_array = js_array_to_php_array(param);
			
			Ajax.mRequest.open( "POST", "/ajax/get_comments.php?param="+php_array, true);
	
			Ajax.mRequest.send( '1' );		
		}
	}
	
	function addComment(pMedia_id, pComment, pSecurityCode, pElementId, pUser_id, pResourceType)
	{	
	
		var Ajax = new AjaxRequest();

		if( Ajax.mRequest )
		{
			Ajax.mId = pMedia_id;
			
			Ajax.mComment = pComment;
			
			Ajax.mUserId = pUser_id;
			
			Ajax.mElementId = pElementId;
			
			Ajax.mpResourceType = pResourceType;
			
			Ajax.addEventListener( REQ_COMPLETE, handleAddComment );

			Ajax.mRequest.open( "POST", "/ajax/save_comment.php?media_id="+pMedia_id+"&security_code="+pSecurityCode+"&comment="+encodeURIComponent(pComment)+"&resource_type="+pResourceType, true);
	
			Ajax.mRequest.send( '1' );		
		}
	}
	
	function deleteComment(pCommentId, pMedia_id, pUser_id, pElementId, pResourceType)
	{	
		var Ajax = new AjaxRequest();

		if( Ajax.mRequest )
		{
			Ajax.mId = pCommentId;
			
			Ajax.mMedia_id = pMedia_id;
			
			Ajax.mUser_id = pUser_id;
			
			Ajax.mElementId = pElementId;
			
			Ajax.mResourceType = pResourceType;
			
			Ajax.addEventListener( REQ_COMPLETE, handleServerResponseDeleteComment );
			
			Ajax.mRequest.open( "POST", "/ajax/delete_comment.php?comment_id="+pCommentId+"&media_id="+pMedia_id+"&user_id="+pUser_id, true);
	
			Ajax.mRequest.send( '1' );		
		}
	}
	
	function addFavorite(pUser_id, pMedia_id, pType, pElementId)
	{
		var Ajax = new AjaxRequest();
		
		if( Ajax.mRequest )
		{
			Ajax.mUser_id = pUser_id;
			
			Ajax.mMedia_id = pMedia_id;
			
			Ajax.mType = pType;
			
			Ajax.mElementId = pElementId;
			
			Ajax.addEventListener( REQ_COMPLETE, handleServerResponse );
			
			Ajax.mRequest.open( "POST", "/ajax/add_to_favorites.php?user_id="+pUser_id+"&media_id="+pMedia_id+"&type="+pType, true);
	
			Ajax.mRequest.send( '1' );		
		}
	}
	
	function handleAddComment(pAjax)
	{
		var obj = document.getElementById( pAjax.mElementId );
		if (pAjax.mRequest.status == 200)
		{
				var result	= pAjax.mRequest.responseText.split("|");
				var status	= result[0];
				var error	= result[1];
				if (status == '1')
				{
					document.getElementById('comment_txt').value			= '';
					document.getElementById('comment_length').value			= 255;
					document.getElementById('security_code_field').value	= '';
					
					//Display user comments using AJAX
				    getComments(pAjax.mId, 0, pAjax.mUserId, 'photoCommentTextUser', pAjax.mpResourceType);
				}

				obj.innerHTML = error;
		}
		else
		{
			obj.innerHTML = "There was a problem accessing the server, please try again ";
		}	
	}
	
	
	// executed automatically when a message is received from the server
	function handleServerResponse( pAjax )
	{
		// status of 200 indicates the transaction completed successfully
		var obj = document.getElementById( pAjax.mElementId );
		if (pAjax.mRequest.status == 200)
		{
			obj.innerHTML = pAjax.mRequest.responseText;
		}
		else
		{
			obj.innerHTML = "There was a problem accessing the server, please try again ";
		}
	}
	
	// executed automatically when a message is received from the server
	function handleServerResponseDeleteComment( pAjax )
	{
		// status of 200 indicates the transaction completed successfully
		var obj = document.getElementById( pAjax.mElementId );
		if (pAjax.mRequest.status == 200)
		{
			obj.innerHTML = pAjax.mRequest.responseText;
			//Display user comments using AJAX
    		getComments(pAjax.mMedia_id, 0, pAjax.mUser_id, 'photoCommentTextUser', pAjax.mResourceType);
		}
		else
		{
			obj.innerHTML = "There was a problem accessing the server, please try again ";
		}
	}
	

// ###### END of AJAX stuff ****************************************************


	function show_search(show,hide1,hide2)
	{
	   	var obj = document.getElementById("search_"+show);
	   	obj.style.display = "block";
	   	var obj = document.getElementById("search_"+hide1);
	   	obj.style.display = "none";
	   	var obj = document.getElementById("search_"+hide2);
	   	obj.style.display = "none";
	}
	
	function show_menu(show_name, hide_name1, hide_name2)
	{
		var obj = document.getElementById("gallery_menu_"+show_name);
	   	obj.style.display = "block";
	   	hide_menu(hide_name1);
	   	hide_menu(hide_name2);
	}
	
	function hide_menu(name)
	{
		var obj = document.getElementById("gallery_menu_"+name);
	   	obj.style.display = "none";
	}
	    
	function add_to_favorites(user_id, media_id, type)
	{
		addFavorite(user_id, media_id, type, 'add_to_favorites_message');
	}
	
	function check_length()
	{
		var maxsize = 255;
		var comment = document.getElementById('comment_txt').value;
		var length = comment.length;
	
		if(length>maxsize)
		{
			alert('Comment is too long! Maximum '+maxsize+' characters.');
			document.getElementById('comment_txt').value = comment.substr(0,maxsize);
		} else {
			document.getElementById('comment_length').value = maxsize - length;
		}
	}
	
	function save_comment(resource_type)
	{
		var media_id		= document.getElementById('media_id').value;		
		var comment			= document.getElementById('comment_txt').value;
		var security_code	= document.getElementById('security_code_field').value;
		var user_id			= document.getElementById('user_id').value;
			
		addComment(media_id, comment, security_code, 'photoCommentResponseText',user_id, resource_type);
	}



function changeView(media_id, city, country, style, gender, venue, store, brand, comment, upload_info, top_rated, editor_pick, style_brand_price, user_id, pElementId)
{
	//Clear success/unsucees message from the 'pgeMain' if exists 
	var my_div = document.getElementById('photoCommentResponseText');
	if (my_div)
		my_div.innerHTML = '';

	// security image refresh
	var security_code_image = document.getElementById('security_code_image');
	if (security_code_image)
	{
		security_code_image.src = '/assets/tools/streamSecurityImage.php?width=130&height=20&rand='+Math.random();
	}

	// empty security field
	var security_code_field = document.getElementById('security_code_field');
	if (security_code_field)
	{
		security_code_field.value = '';
	}	

	// empty security field
	var comment_txt = document.getElementById('comment_txt');
	if (comment_txt)
	{
		comment_txt.value = '';
	}	
		
	var my_div = document.getElementById('add_to_favorites_message');
	if (my_div)
		my_div.innerHTML = '';
	
	//Change media ID for the FORM [add comment]
    var my_media_id = document.getElementById('media_id');
    if (my_media_id)
		my_media_id.value = media_id;
		
    //Display user comments using AJAX
    getComments(media_id, 0, user_id, pElementId, 'media');

    var view_img, city_tag, style_tag, container_obj, details_str, obj
    
    view_img = document.getElementById('view_img');
    view_img.src = media_base_uri + '/' + media_id + '/view'
    
    //Change onclick values for 'Edit this photo'
    obj = document.getElementById('edit_photo_link');
    if ( obj )
    {
        if ( navigator.appName == 'Netscape' )
        {
            obj.onclick = eval('function () { open_admin_popup(' + media_id + '); return false; }')
        }
        else
        {
            obj.setAttribute('onclick',function(){open_admin_popup(media_id);return false;});
        }
    }
    
    //Change onclick values for 'Add to favorites'
    obj = document.getElementById('add_to_favorites');
    if ( obj )
    {
        if ( navigator.appName == 'Netscape' )
        {
            obj.onclick = eval('function () { add_to_favorites('+user_id+','+media_id+',"media"); return false; }')
        }
        else
        {
            obj.setAttribute('onclick',function(){add_to_favorites(user_id,media_id,"media");return false;});
        }
    }
    
    //Change onclick values for 'Log in to post comments.' [if not logged]
    obj = document.getElementById('must_login_link');
    if ( obj )
    {
    	obj.href = '/-/user/login/comment?media_id='+media_id;
    }
    
    
    details_str = '';
    details_str += '<table cellpadding="3" cellspacing="3" border="0" width="100%">';
    
    /* city */
    if ( city )
        details_str += '<tr><td valign="top" class="imgDetailHeading">' + tag_titles['city']  + ': </td><td colspan="2"><strong>' + city + ', ' + country + '</strong></td></tr>';    
    /* store */
    if ( store )
        details_str += '<tr><td valign="top" class="imgDetailHeading">' + tag_titles['store'] + ': </td><td colspan="2"><strong>' + store + '</strong></td></tr>';                                                                                                             
    /* store */
    if ( venue )
        details_str += '<tr><td valign="top" class="imgDetailHeading">' + tag_titles['venue'] + ': </td><td colspan="2"><strong>' + venue + '</strong></td></tr>';                                                                                                             
    /* gal, brand, price */                                                                                                             
    if ( style_brand_price ) {              
        for(var i = 0; i < style_brand_price.length; i++){                            
        		details_str += '<tr><td valign="top" class="imgDetailHeading">' + style_brand_price[i][0] + ': </td><td><strong>' + style_brand_price[i][1]  + '</strong></td><td><span class="imgDetailHeading">Price: </span><strong>' + style_brand_price[i][3] + ' ' + style_brand_price[i][2] + '</strong></td></tr>';
        }          
    }            
    /* empty row */
        details_str += '<tr><td colspan="3">&nbsp;</td></tr>';                 
    /* uploaded */                     
    if ( upload_info )
        details_str += '<tr><td valign="top" class="imgDetailHeading">Uploaded: </td><td colspan="2">' + upload_info + '</td></tr>';
    /* style tags */
    if ( style )
        details_str += '<tr><td valign="top" class="imgDetailHeading">Style tags: </td><td colspan="2">' + style  + '</td></tr>'                    
    /* empty row */
        details_str += '<tr><td colspan="3">&nbsp;</td></tr>';                 
    
    details_str += '</table>';
    
    
    container_obj = document.getElementById('photoDetails');
    if ( container_obj )
        container_obj.innerHTML = details_str
    
    if ( container_obj = document.getElementById('photoCommentText') )
        container_obj.innerHTML = comment
    
    if ( container_obj = document.getElementById('photoInfo') )
        container_obj.innerHTML = upload_info
    
    if ( document.getElementById('admin_panel_media_id') )
    {
        document.getElementById('admin_panel_media_id').value      = media_id;
        document.getElementById('admin_panel_top_rated').checked   = top_rated;
        document.getElementById('admin_panel_editor_pick').checked = editor_pick;
    }
    
}

//Not used anymore [last used in Gallery drop downs]
function populateCitySelectOptions(style, cur_city)
{
    var city_select
    var opt
    var city_id
    var idx
    
    city_select = document.getElementById('city_select')
    if ( !cur_city )
        cur_city = city_select.value
    
    while ( city_select.options.length > 1 )
        city_select.options[1] = null
    
    idx = 0
    for ( i = 0; i < all_cities.length; i++ )
    {
        city_id = all_cities[i]['id']
        
        if ( style && !style_cities[style][city_id] )
            continue;
        
        opt = document.createElement('OPTION')
        opt.value = city_id
        opt.text  = all_cities[i]['value']
        city_select.options.add(opt)
        
        if ( cur_city == city_id )
            city_select.selectedIndex = idx + 1
        idx++
    }
}

//Not used anymore [last used in Gallery drop downs]
function populateStyleSelectOptions(city, cur_style)
{
    var style_select
    var opt
    var style_id
    var cat_id
    
    style_select = document.getElementById('style_select')
    if ( !cur_style )
        cur_style = style_select.value
    
    while ( style_select.options.length > 1 )
        style_select.options[1] = null
    
    idx      = 0
    cat_id   = 0
    cat_name = ''
    // We are iterating all styles, and deciding which ones to actually add.
    for ( i = 0; i < all_styles.length; i++ )
    {
        style_id = all_styles[i]['id']
        
        // The decision if to include a category name is delayed to see if we have any items under it included or not.
        if ( style_id.substr(0, 4) == 'cat:' )
        {
            cat_id   = style_id.substr(4)
            cat_name = all_styles[i]['value']
            continue;
        }
        
        if ( city && !city_styles[city][style_id] )
            continue;
        
        if ( cat_id )
        {
            opt = document.createElement('OPTION')
            opt.value = 'cat:' + cat_id
            opt.text  = cat_name
            style_select.options.add(opt)
            
            if ( cur_style == 'cat:' + cat_id )
                style_select.selectedIndex = idx + 1
            idx++
            
            cat_id   = 0
            cat_name = ''
        }
        
        opt = document.createElement('OPTION')
        opt.value = style_id
        opt.text  = all_styles[i]['value']
        style_select.options.add(opt)
        
        if ( cur_style == style_id )
            style_select.selectedIndex = idx + 1
        idx++
    }
}

