function Knot()
{
}

Knot.rateHoverBig = function( domid, rating )
{
	$(domid).src = "http://static.vsocial.com/theknot/022008/images/photo_heart_big_1.gif";
	for (var x = (rating - 1); x>0;x--)
	{
		$("big_rate_" + x). src = "http://static.vsocial.com/theknot/022008/images/photo_heart_big_1.gif";
	}

}
Knot.rateNoHoverBig = function()
{
	$("big_rate_1").src = "http://static.vsocial.com/theknot/022008/images/photo_heart_big_0.gif";
	$("big_rate_2").src = "http://static.vsocial.com/theknot/022008/images/photo_heart_big_0.gif";
	$("big_rate_3").src = "http://static.vsocial.com/theknot/022008/images/photo_heart_big_0.gif";
	$("big_rate_4").src = "http://static.vsocial.com/theknot/022008/images/photo_heart_big_0.gif";
	$("big_rate_5").src = "http://static.vsocial.com/theknot/022008/images/photo_heart_big_0.gif";
}
Knot.rateHover = function( media_id, rating )
{
	$( "small_rate_" + media_id + "_" + rating ).src = "http://static.vsocial.com/theknot/022008/images/pixelheart_1.gif";
	for (var x = (rating - 1); x>0;x--)
	{
		$( "small_rate_" + media_id + "_" + x ). src = "http://static.vsocial.com/theknot/022008/images/pixelheart_1.gif";
	}

}
Knot.rateNoHover = function( media_id )
{
	$( "small_rate_" + media_id + "_1").src = "http://static.vsocial.com/theknot/022008/images/pixelheart_0.gif";
	$( "small_rate_" + media_id + "_2").src = "http://static.vsocial.com/theknot/022008/images/pixelheart_0.gif";
	$( "small_rate_" + media_id + "_3").src = "http://static.vsocial.com/theknot/022008/images/pixelheart_0.gif";
	$( "small_rate_" + media_id + "_4").src = "http://static.vsocial.com/theknot/022008/images/pixelheart_0.gif";
	$( "small_rate_" + media_id + "_5").src = "http://static.vsocial.com/theknot/022008/images/pixelheart_0.gif";
}
Knot.voteEntry = function( media_id, meta_type )
{
	new Ajax.Request( '/media/_vote/media_id=' + media_id + '&media_type=' + meta_type,
	{
		method: 'get',
		onLoading: function()
		{
			$('votethis_' + media_id).innerHTML = "Saving...";
		},
		onSuccess: function(transport)
		{
			if ( e = $('votethis_' + media_id) ) {
				$('votethis_' + media_id).innerHTML = '<img src="http://static.vsocial.com/theknot/022008/images/2__p2_thanks_vote.jpg"/>';
			}
		}
	});

}
Knot.voteEntryEx = function( media_id, meta_type )
{
	new Ajax.Request( '/media/_vote/media_id=' + media_id + '&media_type=' + meta_type,
	{
		method: 'get',
		onLoading: function()
		{
			$('votethis_' + media_id).innerHTML = "Saving...";
		},
		onSuccess: function(transport)
		{
			if ( e = $('votethis_' + media_id) ) {
				$('votethis_' + media_id).innerHTML = '<img src="http://static.vsocial.com/theknot/022008/images/2__p2_thanks_vote_vid.jpg"/>';
			}
		}
	});

}
Knot.rateEntryEx = function( media_id, rating )
{
	new Ajax.Request( '/media/_rate/media_id=' + media_id + '&rating=' + rating,
	{
		method: 'get',
		onLoading: function()
		{
			$('ratethis_' + media_id).innerHTML = "Saving...";
		},
		onSuccess: function(transport)
		{
			if ( e = $('ratethis_' + media_id) ) {
				Knot.ajaxUpdate( e, '/partials/new_avgrating/media_id=' + media_id );
				Knot.ajaxUpdate( $('currate_' + media_id), '/partials/new_rating/media_id=' + media_id  );
			}
		}
	});
}
Knot.rateEntry = function( media_id, rating )
{
	new Ajax.Request( '/media/_rate/media_id=' + media_id + '&rating=' + rating,
	{
		method: 'get',
		onLoading: function()
		{
			$('ratethis_' + media_id).innerHTML = "Saving...";
		},
		onSuccess: function(transport)
		{
			if ( e = $('ratethis_' + media_id) ) {
				Knot.ajaxUpdate( e, '/partials/rating/media_id=' + media_id );
				Knot.ajaxUpdate( $('currate_' + media_id), '/partials/avgrating/media_id=' + media_id );
			}
		}
	});
}
Knot.ratePhotoEntry = function( media_id, rating )
{
	new Ajax.Request( '/media/_rate/media_id=' + media_id + '&rating=' + rating,
	{
		method: 'get',
		onLoading: function()
		{
			$('photorate').innerHTML = "Saving...";
		},
		onSuccess: function(transport)
		{
			if ( e = $('curphotorate') ) {
				Knot.ajaxUpdate( e, '/partials/photo_rating/media_id=' + media_id );
				Knot.ajaxUpdate( $('photorate'), '/partials/photo_avgrating/media_id=' + media_id );
			}
		}
	});
}
Knot.deleteEntry = function()
{
	if ( confirm( "Are you sure you wish to remove your entry?  Your entry will lose all ratings, comments and views!" ) )
		new Ajax.Request( '/user/_deleteEntry',
		{
			method: 'get',
			onSuccess: function(transport)
			{
				alert( "Your entry has been removed" );
			}
		});
}
Knot.ajaxUpdate = function( element_id, url )
{
	new Ajax.Updater( element_id, url, { evalScripts: true } );
}

Knot.addMediaComment = function( media_id, media_type, comment )
{
	if ( !comment )
		return;

	var url = '/media/_addComment';
	var params = { media_id: media_id, media_type: media_type, comment: comment };

	new Ajax.Request(url,
		{
			method: 'post',
			parameters: params,
			onSuccess: function(transport)
			{
				$('comment_text').value = '';
				Knot.ajaxUpdate( 'commentbox', '/media/comments/' + media_id );
			}
	  });
}

Knot.addUserComment = function( user_id, comment )
{
	if ( !comment )
		return;

	var url = '/user/_addComment';
	var params = { user_id: user_id, comment: comment };

	new Ajax.Request(url,
		{
			method: 'post',
			parameters: params,
			onSuccess: function(transport)
			{
				$('comment_text').value = '';
				Knot.ajaxUpdate( 'commentbox', '/profile/comments/' + user_id );
			}
	  });
}


Knot.topLoad = function( list, count )
{
	new Ajax.Updater( 'dyn_media', '/partials/nominees/list=' + list + '&count=' + count,
		{
			evalScripts: true,

			onLoading: function()
			{
				$('dyn_media').innerHTML = "<center><br/>Loading...<br/><br/></center>";

				$('list_widget_new').className = '';
				$('list_widget_featured').className = '';
				$('list_widget_rated').className = '';
				$('list_widget_pop').className = '';


			},

			onLoaded: function( transport )
			{

				$('list_widget_' + list).className = 'active';
			}
		});

}



Knot.submitFormUpdate = function( which )
{
	f = ['photo','video','site'];

	for( i = 0; i < f.length; i++ )
		if ( which == f[i] )
		{
			Element.show(f[i] + '_form');
			Element.show(f[i] + '_help');
		}
		else
		{
			Element.hide(f[i] + '_form');
			Element.hide(f[i] + '_help');
		}
}

Knot.userTypeChange = function( which )
{
	if ( which == "bride" || which == "groom" )
	{
		Element.removeClassName( 'company_input', 'validate' );
		Element.hide( 'company_field' );
		Element.hide( 'is_advertiser' );
		$('profile_image_help').innerHTML = "(How about a nice shot of the two of you?)";
	}
	else
	{
		Element.addClassName( 'company_input', 'validate' );
		Element.show( 'company_field' );
		Element.show( 'is_advertiser' );
		$('profile_image_help').innerHTML = "No logos, please.";
	}
}

Knot.validateForm = function( form )
{
	form = $(form);

	var elements = form.getElementsByClassName( "validate" );

	for( i = 0; i < elements.length; i++ )
	{
		element = elements[i];
		validation_type = elements[i].getAttribute( "validate" );
		value = elements[i].value;
		msg = elements[i].getAttribute( "invalid_msg" );

		valid = true;
		validate = elements[i].getAttribute( "validate" );

		if ( validate && ( validate[0] != '@' || ( validate[0] == '@' && value ) ) )
		{
			if ( validate[0] == '@' )
				validate = validate.slice(1);

			switch( validate )
			{
				case "string":
					valid = value;
					break;

				case "numeric":
					valid = value.match( /^[0-9]+$/ );
					break;

				case "email":
					valid = value.match( /^[^\s]+@[^\s]+\.[^\s]+$/ );
					break;

				case "checked":
					valid = element.checked;
					break;

				case "phone":
					valid = ( (value.length == 10 || value.length == 12 ) && ( value.match( /^[0-9]+$/ ) || value.match( /^[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]$/ ) ) );
					break;
			}
		}

		if ( ( verify = element.getAttribute( "verify" ) ) )
			valid = form[verify].value == value;

		if ( !valid )
		{
			alert( msg );
			return false;
		}
	}

	return true;
}

Knot.enableUpload = function () {

    var need_profile = $("need_profile"),
        upload_form  = $("entry_forms");

    if ( need_profile && need_profile.style ) {
        need_profile.style.display = "none";
    }

    if ( upload_form && upload_form.style ) {
        upload_form.style.display = "";
    }
};

Knot.loadProfileThumbnails = function( start_letter, end_letter, page )
{
	var url = '/partials/profile_list/start_letter=' + start_letter + '&end_letter=' + end_letter + '&page=' + page;

	new Ajax.Updater( 'dyn_thumbs', url,
		{
			evalScripts: true,
			onLoading: function()
			{
				$('dyn_thumbs').innerHTML = "<center><br/>Loading...<br/><br/></center>";

				Element.removeClassName( 'profiles_a', 'active' );
				Element.removeClassName( 'profiles_i', 'active' );
				Element.removeClassName( 'profiles_q', 'active' );
			},

			onSuccess: function( transport )
			{
				Element.addClassName( 'profiles_' + start_letter.toLowerCase(), 'active' );
			}
		});
}

Knot.loadThumbnails = function( media_type, listing, term, page )
{
	var url = '/partials/thumbnail_list/media_type=' + media_type + '&listing=' + listing + '&page=' + page;

	if ( term )
		url = url + '&term=' + term;

	new Ajax.Updater( 'dyn_thumbs', url,
		{
			evalScripts: true,
			onLoading: function()
			{
				$('dyn_thumbs').innerHTML = "<center><br/>Loading...<br/><br/></center>";

				Element.removeClassName( 'media_new', 'active' );
				Element.removeClassName( 'media_rated', 'active' );
				Element.removeClassName( 'media_pop', 'active' );
				Element.removeClassName( 'media_popmonth', 'active' );
				Element.removeClassName( 'media_featured', 'active' );
				Element.removeClassName( 'media_finalist', 'active' );
				Element.removeClassName( 'media_photos', 'active' );
				Element.removeClassName( 'media_newnoms', 'active' );
				Element.removeClassName( 'media_popnoms', 'active' );
				Element.removeClassName( 'media_ratednoms', 'active' );
				Element.removeClassName( 'media_videos', 'active' );
				
				Element.removeClassName( 'best', 'active' );
				Element.removeClassName( 'best_bp', 'active' );
				Element.removeClassName( 'best_vid', 'active' );
				Element.removeClassName( 'best_vid_bp', 'active' );
				Element.removeClassName( 'best_dest', 'active' );
				Element.removeClassName( 'best_cake', 'active' );
				Element.removeClassName( 'best_bouq', 'active' );
			},

			onLoaded: function( transport )
			{
				Element.addClassName( 'media_' + listing, 'active' ); //TODO: UNCOMMENT WHEN FINISHED P2!!!!
				Element.addClassName( listing, 'active' );
			}
		});
}

Knot.deleteEntry = function( entry_id, force )
{
	if ( !force && !confirm( "Are you sure you want to delete this entry?" ) )
		return false;

	new Ajax.Request( '/media/_delete/media_id=' + entry_id,
	{
		method: 'get',
		onSuccess: function(transport)
		{
			Element.hide( 'entry_' + entry_id );
			alert( "Your entry has been deleted" );
            window.location.reload();
		}
	});
}

Knot.deleteShot = function( shot_id, entry_id )
{
    if ( $("entries_photos").getElementsByTagName("table").length > 1 ) {

        if ( ! confirm( "Are you sure you want to delete this screenshot?" ) ) {
            return false;
        }
	}
    else {
        if ( ! confirm( "If you delete this screenshot, the entire entry will be deleted.\n\nContinue?" ) ) {
            return false;
        }

        return Knot.deleteEntry(entry_id, true);
    }

	new Ajax.Request( '/media/_delete/media_id=' + shot_id,
	{
		method: 'get',
		onSuccess: function(transport)
		{
			Element.hide( 'entry_' + shot_id );
			alert( "Your screenshot has been deleted" );
            window.location.reload();
		}
	});
}

Knot.deletePhoto = function( photo_id, entry_id )
{
    if ( $("entries_photos").getElementsByTagName("table").length > 1 ) {

        if ( ! confirm( "Are you sure you want to delete this photo?" ) ) {
            return false;
        }
	}
    else {
        if ( ! confirm( "If you delete this photo, the entire entry will be deleted.\n\nContinue?" ) ) {
            return false;
        }

        return Knot.deleteEntry(entry_id, true);
    }

	new Ajax.Request( '/media/_delete/media_id=' + photo_id,
	{
		method: 'get',
		onSuccess: function(transport)
		{
			Element.hide( 'entry_' + photo_id );
			alert( "Your photo has been deleted" );
            window.location.reload();
		}
	});
}

Knot.updateEntry = function( entry_id )
{
	params = Form.serialize( 'frm_edit_' + entry_id, true );

	new Ajax.Request('/media/_updateEntry',
		{
			method: 'post',
			parameters: params,
			onSuccess: function(transport)
			{
				Element.toggle( 'entry_' + entry_id + '_edit' );
				alert( "Your entry has been updated" );
                window.location.reload();
			}
	  });
}

Knot.forgotPassword = function( email )
{
	new Ajax.Request('/user/_resetPassword/email=' + email,
		{
			method: 'get',
			onSuccess: function( transport )
			{
				alert('Your password has been reset and sent to you. Thanks!');
			}
		});
}

Knot.thumbnailListener = function () {

    var next = function(className, node) {
        var n = (node||document).firstChild;

        do {
            if ( n && n.className && n.className.match(new RegExp(className)) ) {
                return n;
            }
        } while ( n = n.nextSibling );

        return null;
    };

    return {
        init: function () {
            var thumbnails = document.getElementsByClassName("thumb_hover");

            for (var i = 0; i < thumbnails.length; i++) {
                (function(){
                    var thumb = thumbnails[i];

                    if ( thumb.$done === true ) {
                        return;
                    }

                    var _showing = false,
                        _text,
                        _timeout = null,
                        _mouseIn = function (e) {
                            if (_timeout) {
                                window.clearTimeout(_timeout);
                            }

                            // show the mask
                            if ( _showing !== false) {
                                return;
                            }

                            _showing = true;

                            // find the div to display
                            _text = next("thumb_hover_mask", this);

                            if ( _text ) {
                                _text.style.display = "block";
                                return;
                            }

                            _showing = false;
                        },

                        _mouseOut = function (e) {
                            // remove mask
                            _timeout = setTimeout( function () {
                                if ( _text ) {
                                    _text.style.display = "none";
                                    _text = false;
                                }

                                _showing = false;
                            }, 400);
                        };

                    Event.observe(thumb, "mouseover", _mouseIn);
                    Event.observe(thumb, "mouseout", _mouseOut);

                    thumb.$done = true;
                })();
            }

            return this;
        }
    };
}();

Knot.incrementView = function () {

    var anchors = document.getElementsByTagName("a"),
        hash = location.hash.slice(1);

    for (var i = 0; i < anchors.length; i++) {
        if (anchors[i].getAttribute("name") == hash) {
            var id = parseInt(hash.replace(/\D*/, ""));

            if (isNaN(id)) {
                return;
            }

            new Ajax.Request( '/media/_view/id=' + id,
            {
                method: 'get'
            });

            return;
        }
    }
};

(function(){
    _oldF = window.onload || function(){};
    window.onload = function(e) {
        _oldF.apply(this, arguments);

        Knot.thumbnailListener.init();
        Knot.incrementView();

        var myObjects = document.getElementsByTagName("embed");
        for (var i = 0; i < myObjects.length; i++) {
            myObjects[i].outerHTML = myObjects[i].outerHTML;
        }
    }
})();


function open_popup(url, w, h, resize, scroll,wname) {
/* place this in onclick or href:  "javascript:open_popup('[url]','[width of window]','[height of window]','[resize option]','[scroll opiton]','[windowname]');"  */
  wname = (wname == null) ? "popwin" : wname.replace(new RegExp(/ /g), "");

  scroll = ((scroll == null)||(scroll=='')||(scroll==1)||(scroll=='1'))? 'yes':'no';
  resize = ((resize == null)||(resize=='')||(resize==1)||(resize=='1'))? 'yes':'no';
  var properties = "toolbar=0,scrollbars="+scroll+",location=0,statusbar=1,menubar=0,resizable="+resize;
  properties += ",width="+ w +",height="+ h;
  child = window.open(url,wname,properties);
  child.focus();
}

function CreateBookmarkLink() {
	title = document.title;url=location.href;
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
		} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
	return true; }
}