﻿// global namespace
var DMG = {};
//console.log();
 DMG.createHelp = function()
 {
   

   
   $('.tt').each(function () {
       
        var address =  $(this).attr('id');      
        var x = address.indexOf("_");
        var y = address.substring(0, x);
        
        $(this).qtip({
            content: {
              url: '/Help/' + y,
              method: 'get'
            },
            show: 'mouseover',
            hide: 'mouseout',
            style: { 
              width : { min: 200 },
              tip: 'topLeft',
              name: 'cream'
           }
       });
     
     
    });  
 
 }
 
DMG.normaliseInputs = function (obj)
{
  /*
    This function takes an array of input boxes and makes sure the total
    value does not exceed 100 and that there are no negative numbers.
    WARNING - it does this by subtracting or adding the difference to the
    input box with the largest value, this means it is only appropriate for
    small errors. 
    
    we think this is now fixed.
    
    example:
        normaliseInputs({inputs:[$("#Text1"),$("#Text2"),$("#Text3"),$("#Text4")]});
        
  */
  var checkval = 0;
  var bigVal;
  for (var i = 0; i < obj.inputs.length; i++) {
    //window.console.log(i + " before : " + obj.inputs[i].val());
    var cValue = parseInt(obj.inputs[i].val())
    if (cValue < 0) { 
        obj.inputs[i].val(0);
        cValue = 0;
    }
    if (bigVal == undefined || cValue > bigVal.val()) bigVal = obj.inputs[i];  
    checkval += cValue;
  }
  
  var diff = checkval - 100;
  
  if (diff < 0) bigVal.val(parseInt(bigVal.val())-diff);
  
  for (var i = diff; i > 0; ) {
    for (var j = 0; j < obj.inputs.length; j++) {
        if (obj.inputs[j].val() > 0 && i > 0) {
            obj.inputs[j].val(obj.inputs[j].val()-1);
            i--;
        } 
    }
  }
  
//  for (var i = 0; i < obj.inputs.length; i++) {
//    window.console.log(i + " after : " + obj.inputs[i].val());
//  }
}

DMG.SLIDER ={ current1 : 0, current2 : 0 , current3 : 0  , current4 : 0 , current5 : 0 , current6 : 0 , current7 : 0 , current8 : 0, current9 : 0}

        function filldate()
                {
             var startdate = $("#CampaignStartdate").val();
             //alert(startdate);             
             var sy =  startdate.substring(0,4);
             var sm = startdate.substring(5,7);
             var sd = startdate.substring(8,10);            

             var sdate = new Date(sy,sm-1,sd);
            //  alert(d);            
             var d = new Date(sdate.getTime() + (91*24*60*60*1000));
                        
             var ed   = d.getDate();
             var em = d.getMonth();
             var emm = em + 1;
             
            
             var ey  = (d.getYear()).toString();
             var mo = ( d.getDate() ). toString();   
             var mi = emm.toString();         
          
             if(mo.length == 1)
             {
               var ed = 0 + ed.toString();
             }
             if(mi.length == 1)
             {
              var emm = 0 + emm.toString();
             }
            //alert("ey:" + ey);
            if(ey.length == 3)
             {
               var ey = 20 + ey.substring(1,3);
             }
          
            //alert("after ey:" + ey);
            var  enddatestr   = ey + "-" + emm + "-" + ed;
            

             //alert(enddatestr);
            $("#CampaignEnddate").val(enddatestr);
             
              }

/****** On Window loaded ******/
$(window).bind('load', function () {
//once window is fully loaded including all images etc
    $(".imgover").each( 
        function () {
            $('<img />')
            .attr('src', this.src.replace(".png","x.png"))           
            .load(function(){
                $('#hidden').append( $(this) );
            });
        }); 
      
    $(".imgovergif").each( 
        function () {
            $('<img />')
            .attr('src', this.src.replace(".gif","x.gif"))           
            .load(function(){
                $('#hidden').append( $(this) );
            });
        });  
      
      
      
});

$(document).ready(function () {

    $(".imgover")
    .hover(
        function () {
            this.src = this.src.replace(".png", "x.png");
            this.src = this.src.replace(".gif", "x.gif");
        },
        function () {
            this.src = this.src.replace("x.png", ".png");
            this.src = this.src.replace("x.gif", ".gif");
        }
    );

    $(".imgovergif")
    .hover(
        function () {

            this.src = this.src.replace(".gif", "x.gif");
        },
        function () {

            this.src = this.src.replace("x.gif", ".gif");
        }
    );

    $('.PayMe').click(function () {
        //send payment request
        var id = $(this).attr('id');
        var result = id.split("_");
        alert(result);
        var pid = result[0];
        alert(pid);
        var amount = result[1];
        alert(amount);

        $.ajax({
            url: "/Data/PaymentRequest/" + pid,
            type: "POST",
            dataType: "text",
            data: {},
            error: function (request) {
                alert("error");
            },
            success: function (request) {
                //disable the payme button                                  
                alert("Payment requested to Swarm");
                $('.PayMe').attr("disabled", true);

            }
        });
    });


    $("#CampaignStartdate").datepicker({ dateFormat: 'yy-mm-dd' });
    $("#CampaignEnddate").datepicker({ dateFormat: 'yy-mm-dd' });
    $("#CampaignEnddate1").datepicker({ dateFormat: 'yy-mm-dd' });



    DMG.createHelp();

    $('.login_up').click(DMG.PopWeezard);

    // $('.myaccount').click(DMG.PopWeezard);


    $('.closeimage').live("click", function () {
        DMG.CloseWeezard();
    });

    $('.clearimage').live("click", function () {

        // $(this).parent().parent().hide('fast'); 
        // alert($(this).closest('.close').attr("id"));
        $(this).closest('.close').hide('fast');




    });

    $('#SiteSearchButton').click(function () {
        var data = $('.searchfilterinput').serializeArray();
        //$('.accordion').next().remove();
        $("<div />").load('/Data/SearchSites', data, function () {
            $(this).hide().prependTo('#data').slideDown('slow');
        });
    });

    $('#AssignSiteSearchButton').click(function () {
        var data2 = $('.searchfilterinput').serializeArray();
        $("<div />").load('/Data/AssignSearchSites', data2, function () {
            $(this).hide().prependTo('#data').slideDown('slow');
        });
    });

    $('#CampaignSearchButton').click(function () {

        var data1 = $('.searchfilterinput1').serializeArray();

        //  $('.accordion').next().remove();

        $("<div />").load('/Data/SearchCampaigns', data1, function () {

            $(this).hide().prependTo('#data').slideDown('slow');
        });
    });
    $('#CampaignSearchButtonp').click(function () {

        var data1 = $('.searchfilterinput1').serializeArray();

        //  $('.accordion').next().remove();

        $("<div />").load('/Data/SearchCampaignsPublisher', data1, function () {
            $(this).hide().prependTo('#data').slideDown('slow');
        });
    });

    //this needs to happen before the corners - expander for the table headers
    $('.accordion').live("click", DMG.AccordianHeadsHandler);


    $('.starthidden').next().hide();

    //	$('.starthidden').append("<span class='accordiantext'>down</span>").hover(
    //	    function () {
    //	        $(this).find("span.accordiantext").toggle();
    //	    },
    //	    function () {
    //	        $(this).find("span.accordiantext").toggle();
    //	    });


    //ohk lets do the corners


    $('.signIn').each(function () {
        $(this).corners("8px bottom");
    });
    $('.rounded').each(function () {
        $(this).corners("5px");
    });
    $('.roundedBottom').each(function () {
        $(this).corners("5px bottom");
    });
    $('.roundedTop').each(function () {
        $(this).corners("5px top");
    });

    $('.round').each(function () {
        $(this).corners("12px top");
    });
    $('.roundbottom').each(function () {
        $(this).corners("5px bottom");
    });

    $('.joinswarm').each(function () {
        $(this).corners("4px");
    });


    $('.ContactContainer').each(function () {
        $(this).corners("4px");
    });


    $('.LoginFailContainer').each(function () {
        $(this).corners("8px bottom");
    });

    $('#AddSiteWeez').each(function () {
        $(this).corners("8px bottom");
    });

    //copy swap on advertisers button click
    $('#advertisersLink').click(function () {
        $('#copy').toggle();
        $('#advertisersCopy').toggle();
    });

    //bring in the registration form instead of the sign in form
    //    $('.register').click(function () {
    //            $('#formHolder').load('/Account/RegisterPartial',null,DMG.FormCallSwap);            
    //    });

    $('#addSite').click(function () {


        DMG.PopWeezard();
    });
    // $('.editLink').click(DMG.PopWeezard);
    $('.sitecancel').click(function () {
        //alert("sdfds");
        $('#siteName').val("");
        $('#url').val("");
        $('#PaypalAdd').val("");
        $('textarea#Notes').val("");
        $('input:[name=Topic]').attr("disabled", false);
        $('input:[name=Topic]').attr("checked", false);

        DMG.CloseWeezard();
    });

    //weezard - needs refactoring.
    $('#step1 .next').click(function () {

        // $('#url').focus();
        if ($('#url').val() == "") {
            $('#url').valid8('SiteUrl is required');
            $('#url').focus();
            $('#url').blur();

        }




        if ($('#siteName').val() == "") {
            $('#siteName').valid8('SiteName is required');
            $('#siteName').focus();
            $('#siteName').blur();

        }


        if ($('#siteName').val() != "" && $('#url').val() != "") {

            var siteurl = $('#url').val();
            var siteobj = { SiteUrl: siteurl };
            $.post("/Data/CheckForDuplicateSites",
                           siteobj,
                           function (data) {

                               if (data == null) {
                                   //that means it is a new site
                                   if (siteurl.search("wordpress.com") == -1) {
                                       $(this).closest("#step1").hide('slow');
                                       $('#step2').show('slow');
                                   }
                                   else {

                                       $('#notallowed').show();
                                       $('#url').focus();
                                       $('#url').blur();
                                   }
                                   $('#sitealreadyadded').hide();
                               }
                               else {
                                   //alert("This site has already been added");
                                   $('#sitealreadyadded').show();
                                   $('#url').focus();
                                   $('#url').blur();
                               }


                           }, "json");


        }





    });

    $('#step2 .previous').click(function () {
        //$(this).parent().hide('slow');
        $(this).closest("#step2").hide('slow');
        $('#step1').show('slow');
    });
    $('#step2 .next').click(function () {
        var checked = $("input[type=checkbox]:checked").length;

        if (checked < 1) {

            alert("Topic is Required");


        }

        if ((checked >= 1) && (checked < 4)) {


            $(this).closest("#step2").hide('slow');
            $('#step3').show('slow');
        }
    });
    $('#step3 .previous').click(function () {
        //$(this).parent().hide('slow');
        $(this).closest("#step3").hide('slow');
        $('#step2').show('slow');
    });
    $('#step3 .next').click(function () {
        $(this).closest("#step3").hide('slow');
        $('#step4').show('slow');
    });
    $('#step3 .continue').click(function () {
        $(this).closest("#step3").hide('slow');
        $('#step4').show('slow');
    });
    $('#step4 .previous').click(function () {

        $(this).closest("#step4").hide('slow');
        $('#step3').show('slow');
    });

});

DMG.PopEmailWeezard = function() {
    DMG.PopWeezardElement1('#Weezard1');
}

DMG.PopWeezard = function() {
    DMG.PopWeezardElement('#Weezard');
}

DMG.PopWeezardElement = function(element) {
    //center the weezard on the screen
    //alert(element);
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    var verticalscroll = $(window).scrollTop();
    //alert(verticalscroll);
    var popupHeight = $(element).height();
    var popupWidth = $(element).width();
    //centering

    var topPos = (windowHeight / 2 - popupHeight / 2) + verticalscroll;
    if (topPos < 25) topPos = 25;

    $(element).css
	(
	    {
	        "position": "absolute",
	        "top": topPos,
	        "left": windowWidth / 2 - popupWidth / 2
	    }
	);


    // IE6 Hack

    $("#backgroundPopup").css
	(
	    { "height": windowHeight }
	);

    //load the weezard
    $("#backgroundPopup").css({
        "opacity": "0.7"
    });
    $("#backgroundPopup").fadeIn('slow');
    $(element).fadeIn("slow");
}

DMG.PopWeezardElement1 = function(element) {
    //center the weezard on the screen
    //alert(element);
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    var verticalscroll = $(window).scrollTop();
    //alert(verticalscroll);
    var popupHeight = $(element).height();
    var popupWidth = $(element).width();
    //centering

    var topPos = (windowHeight / 2 - popupHeight / 2) + verticalscroll;
    if (topPos < 25) topPos = 25;

    $(element).css
	(
	    {
	        "position": "absolute",
	        "top": topPos,
	        "left": windowWidth / 2 - popupWidth / 2
	    }
	);


    // IE6 Hack

    $("#backgroundPopup1").css
	(
	    { "height": windowHeight }
	);

    //load the weezard
    $("#backgroundPopup1").css({
        "opacity": "0.7"
    });
    $("#backgroundPopup1").fadeIn('slow');
    $(element).fadeIn("slow");
}

DMG.CloseWeezard = function() {
  DMG.CloseWeezardElement('#Weezard');
}

DMG.CloseEmailWeezard = function() {
  DMG.CloseWeezardElement1('#Weezard1');
}

DMG.CloseWeezardElement = function(element) {
  
  //  alert("inside close");
	$("#backgroundPopup").fadeOut('slow');
	$(element).fadeOut("slow");
}
   DMG.CloseWeezardElement1 = function(element) {
  
  //  alert("inside close");
	$("#backgroundPopup1").fadeOut('slow');
	$(element).fadeOut("slow");
}
   
   
//    //ADAM WEEZARD 
//    
//    
//    //Click the button event
//	$("#addSite").click(function()
//	{
//		
//		//centering with css
//		centerPopup();
//		//load popup
//		loadPopup();
//	});
//	
//	
//				
//	//CLOSING POPUP
//	//Click the x event
//	$("#WeezardClose").click(function()
//	{
//		disablePopup();
//	});
//	
//	
//	
//	//navigate thru weez
//	
//	

//    
//    $('#editSiteButton').click(function()
//   {
//        loadEditSite();
//   });
   
   
//   $("#backgroundPopup").click(function(){
//		disableEditSite();
//	});
// 




// //***********WEEZARD***********

////0 means disabled; 1 means enabled;
//var popupStatus = 0;


//function loadPopup()
//{
//	//loads popup only if it is disabled
//	if(popupStatus==0)
//	{
//		$("#backgroundPopup").css({
//			"opacity": "0.7"
//		});
//		$("#backgroundPopup").fadeIn('slow');
//		$("#Weezard").fadeIn("slow");
//		popupStatus = 1;
//	}
//}


//function disablePopup()
//{
//	//disables popup only if it is enabled
//	if(popupStatus==1)
//	{
//		$("#backgroundPopup").fadeOut("slow");
//		$("#Weezard").fadeOut("slow");
//		popupStatus = 0;
//	}
//}

////centering popup
//function centerPopup()
//{
//	//request data for centering
//	var windowWidth = document.documentElement.clientWidth;
//	var windowHeight = document.documentElement.clientHeight;
//	var popupHeight = $("#Weezard").height();
//	var popupWidth = $("#Weezard").width();
//	//centering
//	$("#Weezard").css
//	(
//	    {
//		    "position": "absolute",
//		    "top": windowHeight/2-popupHeight/2,
//		    "left": windowWidth/2-popupWidth/2
//	    }
//	);
//	// IE6 Hack
//	
//	$("#backgroundPopup").css
//	(
//	    {"height": windowHeight}
//	);
//	
//}

//function loadEditSite()
//   {
//        if(popupStatus==0)
//	{
//		$("#backgroundPopup").css({
//			"opacity": "0.7"
//		});
//		$("#backgroundPopup").fadeIn('slow');
//		$("#editSite").fadein('slow');
//	}
//   
//   }
//function disableEditSite()
//{
//    if(popupStatus==1)
//    {
//        $('#backgroundPopup').fadeout('slow');
//        popupStatus==0;
//    }
//}



DMG.AccordianHeadsHandler = function() {
    
    
		//$('.accordion').next('.dropShadow').remove();
		
		
		$(this).nextAll('.datacontainer').slideToggle('fast');
		$(this).find(".expander").toggle();
		return false;
	
}
	
	
/****** 
 * display movie on element click
 * alex 27.5.2009
 *******/

DMG.expandMovie = function(obj) {

    var that = this;
    var id = obj.id;
    var element = $('#' + id);
    var movie = obj.movie;

    that.show = function() {

        if (!$('#movieholder').length) {
            //if no holder exists then create the holder
            $('div:last').after('<div id="movieholder"><div id="movieclose">close &raquo;&nbsp;&nbsp;</div><div id="playerdiv"></div></div>');
        }

        //set the close event
        $('#movieclose').click(function() { that.hide(); });

        //position the holder
        var xe = $('#movieholder');
        if (xe.is(":visible")) {
            $('#playerdiv').empty();
            xe.animate({ top: element.offset().top - 18, "left": element.offset().left },500);
        }
        else {
            xe.css({ 'top': element.offset().top - 18, "left": element.offset().left, 'position': 'absolute' });
        }
        //show the holder
        xe.show(500, function() {
            //on complete write the movie into the holder
            var so = new SWFObject('/Content/Flash/mediaplayer.swf', 'mpl', '200', '155', '9', '#000000');
            so.addParam('allowfullscreen', 'false');
            so.addParam('allowscriptaccess', 'always');
            so.addVariable('file', '' + movie + '');
            so.addVariable('height', '155');
            so.addVariable('width', '200');
            so.addVariable('displayheight', '155');
            so.addVariable('displaywidth', '200');
            so.addVariable('frontcolor', '0xffffff');
            so.addVariable('backcolor', '0x000000');
            so.addVariable('lightcolor', '0xff6600');
            so.addVariable('shuffle', 'false');
            so.addVariable('overstretch', 'true');
            so.addVariable('autostart', 'true');
            so.addVariable('searchbar', 'false');
            so.addVariable('controlbar', 'none');
            so.write('playerdiv');

        });




    }

    that.hide = function() {
        //unload player
        $('#playerdiv').empty();
        $('#movieholder').hide(500);
    }

    return {
        init: function() {

            element.click(
                function() {

                    that.show();
                }
            );
        } (),
        show: that.show,
        hide: that.hide
    }
};
