﻿//Placed outside .ready for scoping
var targetX, targetY;
var tagCounter = 0;
$(document).ready(function() {
    //Dynamically wrap image
    $(".PhotoLabel").wrap('<div id="tag-wrapper"></div>');

    //Dynamically size wrapper div based on image dimensions 510px × 338px
   //     $("#tag-wrapper").css({ width:'521px', height:'350px'  });
   $("#tag-wrapper").css({ width: $("#ctl00_ContentPlaceHolder1_mid_image").outerWidth(), height: $("#ctl00_ContentPlaceHolder1_mid_image").outerHeight() });

if($("#ctl00_ContentPlaceHolder1_mid_image").outerWidth() < 450)
{
    $("#tag-wrapper").css("margin", "0 50px 0px");
}
else if($("#ctl00_ContentPlaceHolder1_mid_image").outerWidth() > 450 && $("#ctl00_ContentPlaceHolder1_mid_image").outerWidth() < 500 )
{
    $("#tag-wrapper").css("margin", "0 20px 0px");
}
else
{
    $("#tag-wrapper").css("margin", "0 0px 0px");
}

    //Append #tag-target content and #tag-input content
    $("#tag-wrapper").append('<div id="tag-target"></div><div id="tag-input"><label for="tag-name">Find a Friend To Tag:</label><input type="text" id="tag-name"><button type="button">Add</button><button type="reset">Cancel</button></div>');
    $("#tag-input").append($("#arkadas").html());
    var photoLoadid = $("#ctl00_ContentPlaceHolder1_lbPictureId").text();
    $("#phototags-"+photoLoadid+"").fadeIn("slow");
    $("#tag-name").keyup(function(e) {
        var deger = $(this).val();
        var aranacak;
        $(".arkadas li").each(function() {
            aranacak = $(this).text();
            if (aranacak.substring(0, deger.length).toUpperCase() != deger.toUpperCase()) {
                $(this).css("display", "none");
            }
            else {
                $(this).css("display", "");
            }
            //$("#cikti").text(aranacak + " - " + deger);
        });
    });


    //$("#tag-wrapper").click(function(e){
    $(".PhotoLabel").click(function(e) {
  //  if ($('#taggingDone:visible').length > 0)
    if ($('#taggingDone').is(":visible"))
        {
        //Determine area within element that mouse was clicked
        mouseX = e.pageX - $("#tag-wrapper").offset().left;
        mouseY = e.pageY - $("#tag-wrapper").offset().top;

        //Get height and width of #tag-target
        targetWidth = $("#tag-target").outerWidth();
        targetHeight = $("#tag-target").outerHeight();

        //Determine position for #tag-target
        targetX = mouseX - targetWidth / 2;
        targetY = mouseY - targetHeight / 2;

        //Determine position for #tag-input
        inputX = mouseX + targetWidth / 2;
        inputY = mouseY - targetHeight / 2;

        if(inputX > 420)
        {
           inputX = mouseX - (targetWidth * 2) + 15;
        }

        //Animate if second click, else position and fade in for first click
        if ($("#tag-target").css("display") == "block") {
            $("#tag-target").animate({ left: targetX, top: targetY }, 500);
            $("#tag-input").animate({ left: inputX, top: inputY }, 500);
        } else {
            $("#tag-target").css({ left: targetX, top: targetY }).fadeIn();
            $("#tag-input").css({ left: inputX, top: inputY }).fadeIn();
        }
        
         $('.arkadas :checked').each(function() {
           $(this).attr('checked', false);
         });
        //Give input focus
        $("#tag-name").focus();
        }
    });

    //If cancel button is clicked
    $('button[type="reset"]').click(function() {
        closeTagInput();
    });

    //If enter button is clicked within #tag-input
    $("#tag-name").keyup(function(e) {
        if (e.keyCode == 13) return;
    });
    
    /*
     $("#taggingDone").click(function(e) {
      $("#taggingStart").css("display", "");
      $("#taggingDone").css("display", "none");
     });
     */
     
      /*
     $("#taggingStart").click(function(e) {
        var log = $(".arkadas :not(:checked)").size();
        if (log != 0)
        {
      $("#taggingStart").css("display", "none");
      $("#taggingDone").css("display", "");
        }
        else
        {
        FB.getLoginStatus(function(response) {
			if(response.authResponse){
			    if(response.status == 'connected')
			    {
			    window.location.reload(true);
			    }
			}
			else
			{
		$('#LoginTag').css("display", "");
	    $('#LoginTag').slideDown();
	    $('#tag-blocks').hide();
			}
		});
        }
     });
     
      */

    //If submit button is clicked
    $('button[type="button"]').click(function() {
        var name = [];
        var allVal = [];
        var id = [];
        var picurl = [];
        $(".arkadas :checked").each(function() {
           name.push($(this).attr("id"));
           allVal.push($(this).val());
         });
        for(var i=0; i<allVal.length; i++) {
    id[i] = allVal[i].split('$')[0];
    picurl[i] = allVal[i].split('$')[1];
    }
      submitTag(name,id,picurl);   
      loadFeedForTagsNew(id,name);

    });
});

function submitTag(name,id,picurl) {
    var uid = [];
    var txt = [];
    var photoid;
    var pic = [];
    var tagValue = [];
    var deger = "hj";
    if (deger == null) {
        tagValue = $("#tag-name").val();
    }
    else {
        uid = id;
        tagValue = name;
        pic = picurl;
        txt = $("#user").text();
    }
   var targetTagY = targetY + 170;
   var targetTagX = targetX + 77;
   targetY = targetY + 170;
   targetX = targetX + 77;
   
   
   var PhotoIdTag = $("#ctl00_ContentPlaceHolder1_lbPictureId").text();
   if($("#phototags-"+PhotoIdTag+"").text() == "")
   {
   $("#phototags-"+PhotoIdTag+"").append('In This Photo :');
   }
   
   var AlbumId = gup('AlbumId');

   for(var i=0; i<uid.length; i++) {

    //Adds a new list item below image. Also adds events inline since they are dynamically created after page load
       $("#phototags-" + PhotoIdTag + "").append('<span id="hotspot-item-' + uid[i] + '" onmouseover="showTag(' + uid[i] + ')" onmouseout="hideTag(' + uid[i] + ')"><a href="http://www.facebook.com/profile.php?id=' + id[i] + '"> ' + name[i] + '</a> (<a href="http://pictures.discoversd.com/taggedPictures.aspx?profileid=' + id[i] + '">photos</a> | <a href="#" onclick="removeNowTag(' + uid[i] + ')">remove tag</a>)</span>')
    //Adds a new hotspot to image
    $("#phototags-"+PhotoIdTag+"").append('<div id="hotspot-' + uid[i] + '" class="hotspot" style="left:' + targetX + 'px; top:' + targetY + 'px;"><span>' + tagValue[i] + '</span></div>');
    
    ajaxPage("http://pictures.discoversd.com/ajaxPage/PhotoLabel.aspx?TaggedId=" + uid[i] + "&tagValue=" + tagValue[i] + "&Top=" + targetTagY + "px&Left=" + targetTagX + "px&PhotoId=" + PhotoIdTag + "&Action=Add&UserId=" + txt + "&picurl=" + pic[i] + "&albumid=" + AlbumId);
     tagCounter++;
    }
    

    $(".arkadas li").each(function() {
        $(this).css("display", "");
    });
    $(".arkadas li").css("display", "");
    closeTagInput();
}

function closeTagInput() {
    $("#tag-target").fadeOut();
    $("#tag-input").fadeOut();
    $("#tag-name").val("");
}

function removeTag(i) {
    $("#hotspot-item-" + i).fadeOut();
    $("#hotspot-" + i).fadeOut();
    ajaxPage("http://pictures.discoversd.com/ajaxPage/PhotoLabel.aspx?RemoveId=" + i + "&Action=Remove");
}

function removeNowTag(i) {
    $("#hotspot-item-" + i).fadeOut();
    $("#hotspot-" + i).fadeOut();
     var PhotoIdTag = $("#ctl00_ContentPlaceHolder1_lbPictureId").text();
     ajaxPage("http://pictures.discoversd.com/ajaxPage/PhotoLabel.aspx?RemoveId=" + i + "&Action=RemoveNow&PhotoId=" + PhotoIdTag);
}

function showTag(i) {
    $("#hotspot-" + i).addClass("hotspothover");
}

function hideTag(i) {
    $("#hotspot-" + i).removeClass("hotspothover");
}


function ajaxPage(sayfa) {
    var html = $.ajax({
        url: sayfa,
        cache: false,
        async: false
    }).responseText;
    //alert(html);
}


function gup(name)
{
 var results = window.location.href;
 var urlparts = results.split('/');
 var id = urlparts[4];
 var albumid = id.split('a');
  if( urlparts == null )
    return "";
  else
    return albumid[1] ;
}

function loadFeedForTagsNew(id,name) {
    var imageurl = $("#ctl00_ContentPlaceHolder1_mid_image").attr("src");
    var url=window.location.href;
		targets = new Array();
		names = new Array();
		names = name;
		counter = 0;
		targets = id;       
		//alert(targets);
		for(i=0;i<targets.length;i++)
		{
        FB.ui( 
        { method: 'stream.publish', display: 'iframe', message: '', attachment:
                            {     
                                name: names[i] + ' was tagged on a DiscoverSD.com photo album.', caption: 'Click the thumbnail or link above to see the photo', description: ('DiscoverSD.com covers nightlife and special events in San Diego along with featuring reviews and editorials on San Diego’s hottest Restaurants,Venues, Hotels, Boutique Stores and Spas'),
                                href: url,
                                media:[{type: "image",src:imageurl,href: url }]
                            }, action_links: [{ text: 'Sign up', href: 'http://www.discoversd.com/fbregister/'}],
                            target_id: targets[i], user_message_prompt: 'Write something...'
                        },     
                        function(response) {
                          //reload_page();   
                        } );
}

	}
	function reload_page () {
						window.location.reload();
					}

