jQuery.noConflict();

jQuery(function(){
    jQuery('ul.sf-menu').superfish({ 
        animation:   {height:'show'},
        dropShadows: false,
        speed:	'fast'
    }); 
    jQuery('ul.sf-menu2').superfish({ 
        animation:   {height:'show'},
        dropShadows: false,
        speed:	'fast',
        onBeforeShow:		 function (){
               jQuery('ul.mcol3').slideUp('fast');
        }
    }); 
    make_media_type_radio_work();
    make_search_options_work();
}); 

jQuery(
    function() {
        make_media_type_sensitive();
        make_select_all_links_work();
        make_refine_picky();
        make_refine_removal_work();
        make_motion_sensitive()
        accept_terms();
        make_all_untick_work();
        empty_text_field();
        validate_jump_to();
        validate_add_to_lightbox();
        lightbox_name_dropdown();
        add_date_picker();
        postal_method();
        selected_media();
		update_collection();
        refresh_captcha();
        validate_selectmedia();
//  validate_copy_to();
    }
);

function refresh_captcha() {
    jQuery("#refresh_captcha").click(function () {
        var el = jQuery(".captcha_frame");
        el.attr('src', '/email/captcha'); 
        return false;
        });
}


/* 
	Updates righthand side of Collections page with Collection data 
	as selected from Navigator in lefthand side 
	or Features thumbnails 
*/
function update_collection() {
    // var regEx= /collection/;
	// if ( location.pathname.match(regEx) ) {
	
	var pathArray = window.location.pathname.split( '/' );
	
	// Try and account for all the different possible variants of the URL
	if ( pathArray[1] == 'collection' || pathArray[1] == 'collections' || pathArray[2] == 'collections'  ) {
		// If we only want this to be processed on the Collections overview page, not individual Collections pages
		// && (pathArray[2] == undefined || pathArray[2] == "")
		
		// alert('Collections');
		
		jQuery("#collections_navigator a").click(
			function () {
				// Show Featured Collections if not already showing, i.e. on first click in lefthand navigator
				jQuery('#featured_collections_thumbs:hidden').show(400);
			
				// Get collection ID so we can get appropriate fragment			
				var collection_id = jQuery(this).attr('id').substr(11);
				// alert('clicked '+collection_id);

				get_collection_html(collection_id, '.wide_col');

				// Circumvent clickthrough to link's href
				return false;
			}
		);
		
		jQuery("#featured_collections_thumbs a").click(
			function () {
				// Get feature ID so we can get appropriate fragment			
				var collection_id = jQuery(this).attr('id').substr(8);

				get_collection_html(collection_id, '.wide_col');

				// Circumvent clickthrough to link's href
				return false;
			}
		);
    }
}

/* 
	Does the heavy loading for update_collection() above. 
	id is the db id for the relevant Collection
	to_where is a jQuery collection reference 
*/
function get_collection_html(id, to_where) {
	// build our HTML object
	var collection_new = '';
					
	jQuery.getJSON('/ajax/collection/'+id, function(data) {
	  	// Should only get back 1 result, so no need to loop
		// console.log(data);

		collection_pop_up = "javascript:popUpWindow('/media/"+ data.main_media_id +"/view')";// Difficult to add this to collection_new inline due to '" clash
		
		collection_is_new = '';
		collection_rights_managed = '';
		collection_logo = '';
				
		if(data.is_new){
			collection_is_new = '<span class="new">New</span>';
		}
							
		if(data.rights_managed){
			collection_rights_managed = '<acronym class="license_type" title="Rights Managed">RM</acronym>';
		}
		
		if(data.logo){
			collection_logo = '<img src="/static/media/images/collections/logos/'+ data.logo +'" class="logo_collection" alt="'+ data.title + '" />';
		}
		
		// Split Summary on line breaks
		collection_summary = data.summary.split("\n\n");
		// Wrap in <p> tags
		jQuery.each(collection_summary, function(index, value) { 
			collection_summary[index] = '<p>'+ value +'</p>';
		});
		// And then output
		collection_summary = collection_summary.join('');	
		// alert(collection_summary);
		
		collection_new = '<div id="slide">'+
		
			'<a href="/media/'+ data.main_media_id +'/view" onclick="'+ collection_pop_up +';return false;" title="'+ data.caption + '"> '+
			'	<img src="/static/media/images/collections/main/'+ data.image +'" class="" width="567" height="457" alt="'+ data.caption +'" /> '+
			'</a>'+

			'<p class="caption bot_margin_20">'+ data.caption +'</p> '+

			'<a href="/collection/'+ data.template +'/list" class="view_collection" title="View this collection"> '+
			'	<img src="/static/media/images/collections/button-view.gif" class="" width="68" height="30" alt="View this collection" /> '+
			'</a> '+

			'<h2 class="bot_margin_20"> '+
			'	<a href="/collection/'+ data.template +'/list" class="title_collection"> '+
			'		 '+ collection_is_new +' '+ data.title +' '+ collection_rights_managed +
			'	</a> '+
			'</h2> '+

			'<div class="summary_collection">' + 
				collection_summary + 
			'</div>' +
			
			collection_logo +
			
			'</div>';
			
		// console.log(collection_new);
		
		// Update to_where
		// jQuery(to_where).html(collection_new);
		
		// Before load data, destroy the gallery to ensure previous Cycle is eradicated - or could also just 'stop' it
		jQuery('.wide_col').cycle('destroy');		
		//jQuery('.wide_col').cycle('stop');
		
		// Need to get rid of any extra items, if there are extra
		// if are then, because we're using append to add items (and that adds at end of existing siblings in parent), 
		// newer items will be at end, whilst earlier are at beginning,
		// so the first one will be what would have been the slide before this one
		// And we want to lose that, else Cycle will start from beginning and show it us again
		// Rather than pick up from where we left off.
		if(jQuery('.wide_col').children().length > 1){
			jQuery('.wide_col').children(':first').remove();	
		}
		
		// Add in our new slide - we always need 2 slides or more for Cycle to work
		jQuery(to_where).append(collection_new);
		
		// And perform our transition
		jQuery('.wide_col').cycle({ 
	        fx:      		'fade', 
	        timeout:  		1000,
			delay:         	-2000, 
			autostop:      	1
	    });
	
	});	
}


function user_selection(items) {
    jQuery.ajaxSetup({dataType:'json'}); 
    jQuery.post('/public/user_selection', items, function(data) {
        jQuery("form input:[name='selectedmedia']").val(data.selected);
    } ) 
}

/*
function popup_update_parent() {
    var popup = jQuery("form#order_form input#order");
    var media = jQuery(popup).attr('value');
    popup.change(
        function(event) {
            var bool = jQuery(this).attr('checked');
            var s = jQuery(self.opener.document.forms.searchForm.mediaselect).filter(
                        function(n) {
                            return jQuery(this).attr('value') == media;
                       }
                    );
            s.attr('checked', bool);
        }
    );
}
*/

function selected_media() {
    jQuery("input[name='mediaselect']").change(
        function() {
            var str = 'mediaselect=' + jQuery(this).val() + '&checked=' + jQuery(this).attr('checked') + '&whence=' + this.form.parentNode.id;
            user_selection(str);
        }
    );
}

function make_motion_sensitive() {
    var regEx= /motion/;
    if ( location.pathname.match(regEx) ) {
        jQuery("form#search input:radio[value='images']").attr('checked', 0);
        jQuery("form#search input:radio[value='clips']").attr('checked', 1);
    }
}


function postal_method() {
       jQuery("h3#postal_method_h3").hide();
       jQuery("div#postal_method_div").hide();
       var sel = jQuery("select[name='highres_deliver']");
       sel.click(
            function() {
                if (sel.val() == 'cd') {
                    jQuery("h3#postal_method_h3").show();
                    jQuery("div#postal_method_div").show();
                }
                else {
                    jQuery("h3#postal_method_h3").hide();
                    jQuery("div#postal_method_div").hide();
                }
        });
}

function add_date_picker() {
    var picker = jQuery("input#order_date_field").datepicker({
        minDate: new Date(),
        changeYear: true,
        dateFormat: 'dd MM yy'
    });
}

function lightbox_name_dropdown() {
    jQuery("#lightbox_name").hide();
    jQuery("#lightbox_name2").hide();
    jQuery("form#search_result_actions [name^='lid']").change(
        function(event) {
            //alert(jQuery(this).val()+' '+jQuery(event.target).next('label').html());
            if ( jQuery(this).val() == -2 ) {
                jQuery(event.target).next('label').fadeIn('fast');
            }
            if ( jQuery(this).val() != -2 ) {
                jQuery(event.target).next('label').fadeOut('fast');
            }
        }
    );
}

function validate_selectmedia() {
    var selected;
    jQuery("form#search_result_actions, form#lightbox_manager_actions").submit(function() {
        jQuery.ajaxSetup({dataType:'json', async:false});  // has to be synchronous
        jQuery.get('/public/user_selection', { 'whence': this.parentNode.id }, function(data) {
            selected = data.selected;

        });
        if ( selected > 0 ) {
            return true;
        }
        else {
            set_error_msg('You must select some media to complete this action');
        //    console.log("selected="+selected);
            return false;
        }
    });
}

function validate_add_to_lightbox() {
    jQuery("form#search_result_actions input[name^='add_btn']").click(
        function() {
            var arr = jQuery("form option:selected");
            var lid = jQuery.grep(arr, function(n, i) {
                if (jQuery(n).val() != -1 ) {
                    return n;
                }
            });
            if (  lid.length != 1  ) {
                set_error_msg('Please select a (single) lightbox from one the drop down menus');
                return false;
            }
        }
    );
}


function validate_copy_to() {
    jQuery("form#lightbox_manager_actions [name=copy]").click(
        function() {
            //alert(jQuery("form#lightbox_manager_actions [name=copy_to]").size() );
            if ( jQuery("form#lightbox_manager_actions [name=copy_to]").val() == '_' ) {
                if ( ! jQuery('p[class=form_error]').html() ) {
                    var para = jQuery(document.createElement("p"));
                    para.addClass('form_error');
                    var text = jQuery(document.createTextNode('You must pick a lightbox from the list to copy selected media to.'));
                    para.append(text);
                    var select_bar = jQuery('ul[class=selection_bar]');
                    select_bar.before(para);
                    return false;
                }
                return false;
            }
        }
    );
}

function set_error_msg(msg) {
    var para = jQuery("form#search_result_actions .form_error");
    var text = jQuery(document.createTextNode(msg));
    var select_bar = jQuery('ul[class=selection_bar]');
    if ( para.is('p') ) {
        para.remove();
    }
    para = jQuery(document.createElement("p"));
    para.addClass('form_error');
    para.css( 'margin-left', '0' );
    para.append(text);
    select_bar.before(para);
}

function validate_jump_to() {
    jQuery("form#lightbox_manager_actions [name=show]").click(
        function() {
            if ( jQuery("form#lightbox_manager_actions [name=jumpto]").val() == '_' ) {
                if ( ! jQuery('p[class=form_error]').html() ) {
                    set_error_msg('You must pick a lightbox from the list');
                    return false;
                }
            }   
        }
    );
}

function empty_text_field() {
    jQuery("form input#email").click(
        function() {
            jQuery(this).attr('value', '');
        }
    );
}

function accept_terms() {
    jQuery("form.newsletter input#terms_check").click(
        function() {
            if (! jQuery(this).attr('checked') ) {
                jQuery("form.newsletter input#subscribe_btn").hide("slow");
            }
            else {
                jQuery("form.newsletter input#subscribe_btn").addClass("subscribe_btn_return");
                jQuery("form.newsletter input#subscribe_btn").css("display", "inline");
                jQuery("form.newsletter input#subscribe_btn").show("fast");
            }
        });
}


function make_media_type_radio_work() {
    jQuery('input[name=media_type]:radio').click(
        function() {
            //Which one did they click?
            if(jQuery(this).val() == 'images') {
                jQuery('ul#image_format_filter').show();
                jQuery('ul#motion_format_filter').hide();
            } else {
                jQuery('ul#motion_format_filter').show();
                jQuery('ul#image_format_filter').hide();
            }
        }
    );
}

// Initialise country list jQuery
function make_mcol3_work() {
    jQuery('ul.mcol3').bgiframe();
    jQuery('ul.mcol3').hide();
    jQuery('a#close_countries').click(
        function() {
            jQuery('ul.mcol3').slideUp('fast');     
        }
    );
}

function make_search_options_work() {
    jQuery('#search_options').hide();
    jQuery('#search_options').bgiframe();
    add_search_options_hook();
    add_search_options_close_hook();
}

function add_search_options_hook() {
    jQuery('input[name=keywords]:text,input[name=searchstring]:text').click(
        function() {
            jQuery('div#search_options:hidden').slideDown('medium');
        }
    );
}

function add_search_options_close_hook() {
    jQuery('img#closeSearch').click(
        function() {
            jQuery('div#search_options:visible').slideUp('fast');
        }
    );
}


function make_media_type_sensitive() {
    var regEx= /\/motion/;
    if ( location.pathname.match(regEx) ) {
        jQuery("form#search input:radio[value='image']").attr('checked', 0);
        jQuery("form#search input:radio[value='motion']").attr('checked', 1);
    }
}

function make_channels_sensitive() {
    var regEx = /\/channel\/(\w+)\.html/;
    var res = location.pathname.match(regEx);
    if (res) {
        var str = res[1]+'_channel';
        jQuery("form#search input:checkbox[value='all']").attr('checked', 0);
        if (res[1] == 'technoscience') {
            jQuery("form#search input:checkbox[value=2]").attr('checked', 1);
        }
        else {
            jQuery("form#search input#"+str).attr('checked', 1);
        }
    }
}

function make_refine_picky() {
    /* submit a subcategory search only if selection is a real value */
    jQuery('select#refine_results').change(
        function(){
            if (jQuery(this).val() > 0) {
                jQuery('form#search').submit();
            }
        }
    );
}

function make_refine_removal_work() {
    /* on searching, remove refine/subcategory data */
    jQuery('form#search #search_btn').click(
        function(){
            jQuery("form#search input:hidden[name='oldsearchstring']").remove();
            jQuery("form#search input:hidden[name='subcat']").remove();
            jQuery("form#search input:hidden[name='license']").remove();
            jQuery("form#search").submit();
        }
    );
}

function make_all_untick_work() {
    hook_channel_unticker("#image_category_select input:checkbox[name='channel']");
}

function hook_channel_unticker(path) {
    jQuery(path).click(
        function() {
            if(jQuery(this).val() == 'all') {
                jQuery(path).each(
                    function() {
                        jQuery(this).attr('checked',false);
                    }
                );
                jQuery(path + "[value='all']").attr('checked',true);
            } else {
                jQuery(path + "[value='all']").attr('checked',false);
            }
       }
    );
}

function make_all_toggler(formID,inputClass,val) {
    var form = document.getElementById(formID);
    
    if ( form ) {
        var whence = form.parentNode.id;
        var prefix = 'whence=' + whence + '&amp;checked=' + val;
        return function() {
            var str = prefix;
            var path = 'form#' + formID + ' ' + "input[name='" + inputClass + "']";
            jQuery(path).each(
                function(){
                    jQuery(this).attr('checked',val);
                    str += '&amp;mediaselect=' + jQuery(this).val();
                }
            );
            user_selection( str );
            return false;
        };
    }
    else {
        return false;
    }
}

function make_select_all_links_work() {
    /* 
       Use class not id as this happens twice on page
       Select all visible images.  
    */
    jQuery("form#search_result_actions a.select_all").click(
        make_all_toggler('search_result_actions', 'mediaselect', true)
    );
    /* For the lightbox area */
    jQuery("form#lightbox_manager_actions a.select_all").click(
        make_all_toggler('lightbox_manager_actions', 'mediaselect', true)
    );

    /* Deselect all visible images.*/
    jQuery("form#search_result_actions a.deselect_all").click(
        make_all_toggler('search_result_actions', 'mediaselect', false)
    );
    /* For the lightbox area */
    jQuery("form#lightbox_manager_actions a.deselect_all").click(
        make_all_toggler('lightbox_manager_actions', 'mediaselect', false)
    );
}


